Skip to content

Latest commit

 

History

History
1069 lines (877 loc) · 18 KB

File metadata and controls

1069 lines (877 loc) · 18 KB

All Snippets

Each Snippet belong to a category of prefix. Same prefix can be used for both typescript and javascript files, $ represents each step after tab,

Snippet Categories

Category Prefix Group Description
Pages np Quickly generate dynamic, statically fetched, or revalidated pages with various data fetching methods (axios/fetch) and parameter options
Route Handlers nr Create route handler functions for different HTTP methods (GET, POST, PUT, DELETE) with built-in error handling
Actions na Utilize prebuilt action templates to seamlessly interact with API routes using either axios or fetch
Functions nf Leverage templates for generating Image, Static, and Dynamic Metadata, as well as static params functions
Components nc Get the component templates for loading, notfound, error, image, and many more
Imports ni Import a wide range of Next.js modules and utilities with ease
Declarations nd Quickly declare variables with available templates

Snippets Description

Next.js Page - np

Prefix Body
npfetchStatic
async function ${1:getData}() {
  const res = await fetch("${2:https://...}");

  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }

  return res.json();
}

export default async function Page() {
  const data = await ${1:getData}();

  return <main>${3}</main>;
}
npfetchRevalidate
async function ${1:getData}() {
  const res = await fetch("${2:https://...}", { next: { revalidate: ${3:3600} } });

  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }

  return res.json();
}

export default async function Page() {
  const data = await ${1:getData}();

  return <main>${4}</main>;
}
npfetchdynamic
async function ${1:getData}() {
  const res = await fetch("${2:https://...}", { cache: "no-store" });

  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }

  return res.json();
}

export default async function Page() {
  const data = await ${1:getData}();

  return <main>${3}</main>;
}
npaxiosStatic
import axios from "axios";

async function ${1:getData}() {
  try {
    const response = await axios.get(`${2:https://...}`);
    const {result} = response.data;
    return result;
  } catch (error: any) {
    throw new Error("Failed to fetch data");
  }
}

export default async function Page() {
  const data = await ${1:getData}();

  return <main>${4}</main>;
}
npaxiosDynamic
import axios from "axios";

export const fetchCache = "force-no-store";

async function ${1:getData}() {
  try {
    const response = await axios.get(`${2:https://...}`);
    const  {result} = response.data;
    return result;
  } catch (error: any) {
    throw new Error("Failed to fetch data");
  }
}

export default async function Page() {
  const data = await ${1:getData}();

  return <main>${4}</main>;
}
npaxiosRevalidate
import axios from "axios";

export const revalidate = ${1:3600};

async function ${2:getData}() {
  try {
    const response = await axios.get(`${3:https://...}`);
    const { result } = response.data;
    return result;
  } catch (error: any) {
    throw new Error("Failed to fetch data");
  }
}

export default async function Page() {
  const data = await ${2:getData}();

  return <main>${5}</main>;
}
npparams
export default function Page({ params }: {
  params: { ${1:id}: string };
}) {
  const ${1:id} = params.${1:id};
  return (
    <main>
      ${2}
    </main>
  );
}
npsearchParams
export default function Page({
  searchParams,
}: {
  searchParams: { ${1:id}: ${2:string} };
}) {
  const ${1:id} = searchParams.${1:id};
  return <main>${3}</main>;
}
npparamsSearchParams
export default function Page({
  params,
  searchParams,
}: {
  params: { ${1:paramId}: ${2:string} };
  searchParams: { ${3:searchId}: ${4:string} };
}) {
  const ${1:paramId} = params.${1:paramId};
  const ${3:searchId} = searchParams.${3:searchId};
  return <main>${5}</main>;
}
np
export default function Page() {
	return <main>${1}</main>;
}
npasync
async function ${1:customFunction}() {
  ${2}
}

export default async function Page() {
  const data = await ${1:customFunction}();
  return <main>${3}</main>;
}
nplayout
export default function ${1:Layout}({ children }: {
  children: React.ReactNode;
}) {
  return (
    <section>
      {children}
    </section>
  );
}

Next.js Route Handler - nr

Prefix Body
nrget
import { NextResponse } from "next/server";

export async function GET() {
  try {
    const ${2:result} = await ${1:fetchData()};
    return NextResponse.json({ message: "OK", ${2:result} }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ message: "Error", error }, { status: 500 });
  }
}
nrgetSearchParams
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  const ${1:id} = request.nextUrl.searchParams.get("${1:id}");
  try {
    const result = await ${2:fetchData(${1:id})};
    return NextResponse.json({ message: "OK", result }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ message: "Error", error }, { status: 500 });
  }
}
nrgetParams
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest, {params}: any) {
  const ${1:id} = params.${1:id};
  try {
    const result = await ${2:fetchData(${1:id})};
    return NextResponse.json({ message: "OK", result }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ message: "Error", error }, { status: 500 });
  }
}
nrpost
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
  const ${1:body} = await request.json();
  try {
    const result = await ${2:saveData(${1:body})};
    return NextResponse.json({ message: "OK", result }, { status: 201 });
  } catch (error) {
    return NextResponse.json({ message: "Error", error }, { status: 500 });
  }
}
nrput
import { NextRequest, NextResponse } from "next/server";

export async function PUT(request: NextRequest, {params}: any) {
  const ${1:id} = params.id;
  const ${2:body} = await request.json();
  try {
    const result = await ${3:updateData(${1:id}, ${2:body})};
    return NextResponse.json({ message: "OK", result }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ message: "Error", error }, { status: 500 });
  }
}
nrdelete
import { NextRequest, NextResponse } from "next/server";

export async function DELETE(request: NextRequest, {params}: any) {
  const ${1:id} = params.${1:id};
  try {
    const result = await ${2:deleteData(${1:id})};
    return NextResponse.json({ message: "OK", result }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ message: "Error", error }, { status: 500 });
  }
}

Next.js Actions - na

Prefix Body
naaxiosPost
import axios from "axios";

export async function ${1:axiosPostFunction}(body: ${2:Object}) {
  try {
    const response = await axios.post(`${3:https://...}`, {
      body,
    });
    const { ${4:result} } = response.data;
    return ${4:result};
  } catch (error) {
    throw new Error("${5:Axios Post Error :("});
  }
}
naaxiosGet
import axios from "axios";

export async function ${1:axiosGetFunction}() {
  try {
    const response = await axios.get(`${2:https://:...}`);
    const { ${3:result} } = response.data;
    return ${3:result};
  } catch (error: any) {
    throw new Error("${4:Axios Get Error :("});
  }
}
naaxiosPut
import axios from "axios";

export async function ${1:axiosPutFunction}(id: string, body: ${2:Object}) {
  try {
    const response = await axios.put(`${3:https://}`+id, {
      body,
    });
    const { ${4:result} } = response.data;
    return ${4:result};
  } catch (error: any) {
    throw new Error("${5:Axios Put Error :("});
  }
}
naaxiosDelete
import axios from "axios";

export async function ${1:axiosDeleteFunction}(id: string) {
  try {
    const response = await axios.delete(`${2:https://...}` + id);
    const { ${3:result} } = response.data;
    return ${3:result};
  } catch (error: any) {
    throw new Error("${4:Axios Delete Error :("});
  }
}
nafetchGet
export async function ${1:fetchGetFunction}() {
  try {
    const response = await fetch(`${2:https://:...}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return response.json();
  } catch (error) {
    console.error("${3:Fetch GET error:}", error);
    throw error;
  }
}
nafetchPost
export async function ${1:fetchPostFunction}(body: ${2:Object}) {
  try {
    const response = await fetch(`${3:https://:...}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return response.json();
  } catch (error) {
    console.error("${4:Fetch POST error:}", error);
    throw error;
  }
}
nafetchPut
export async function ${1:fetchPutFunction}(id: string, body: ${2:Object}) {
  try {
    const response = await fetch(`${3:https://...}` + id, {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return response.json();
  } catch (error) {
    console.error("${4:Fetch PUT error:}", error);
    throw error;
  }
}
nafetchDelete
export async function ${1:fetchDeleteFunction}(id: string) {
  try {
    const response = await fetch(`${2:https://...}` + id, {
      method: "DELETE",
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return response.json();
  } catch (error) {
    console.error("${3:Fetch DELETE error:}",

 error);
    throw error;
  }
}

Next.js Functions - nf

Prefix Body
nf
export function ${1:functionName}() {
  ${2}
}
nfdefaultExport
export default function ${1:functionName}() {
  ${2}
}
nfgimageMetaData
export function ${1:generateImageMetadata}({
  params,
}: {
  params: { ${2:} }
}) {
  <div>
     ${3:Content here}
 </div>
}
nfgstaticMetadata
import { Metadata } from "next";

export const metadata: Metadata = {
	title: "${1:Title}",
};
nfgdynamicMetaData
import { Metadata } from 'next';

export async function generateMetadata({
  params,
}: {
  params: { ${1:name}: string };
}) : Promise<Metadata> {
  return {
    title: params.${1:name},
  };
}
nfgstaticParams
export async function generateStaticParams() {
  const ${1:dataList} = await fetch('${2:https://...}').then((res) => res.json());

  return ${1:dataList}.map((data:${3:Object}) => ({
    ${4:param}: data.${4:param},
  }));
}

Next.js Component - nc

Prefix Body
ncloading
export default function ${1:Loading}() {
  return <p>${2:Loading...}</p>;
}
ncnotFound
export default function ${1:NotFound}() {
  return (
    <div>
      <h2>${2:Not Found}</h2>
    </div>
  );
}
ncerror
'use client';

export default function ${1:Error}({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <div>
      Error: {error.message}
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}
ncimage
import Image from 'next/image';

export default function ${1:Page}() {
  return (
    <Image
      src="${2}"
      width={$3}
      height={$4}
      alt="${5}"
    />
  );
}
nclink
import Link from 'next/link';

export default function ${1:Page}() {
  return (
    <Link href="/${2}">
      ${3:Link Text}
    </Link>
  );
}
ncscript
import Script from 'next/script';

export default function ${1:Page}() {
  return (
    <>
      <Script src="${2}" />
    </>
  );
}

Next.js Declarations - nd

Prefix Body
ndfetchStaticData
const ${1:staticData} = await fetch("${2:https://...}", { cache: 'force-cache' });
ndfetchDynamicData
const ${1:dynamicData} = await fetch("${2:https://...}", { cache: 'no-store' });
ndfetchRevalidatedData
const ${1:revalidatedData} = await fetch("${2:https://...}", {
  next: { revalidate: ${3:10} },
});

Next.js Imports - ni

Prefix Body
niuseRouter
import { useRouter } from "next/navigation";
nicookies
import { cookies } from "next/headers";
nidraftMode
import { draftMode } from "next/headers";
niheaders
import { headers } from "next/headers";
niimageResponse
import { ImageResponse } from "next/server";
niresponse
import { NextResponse } from "next/server";
nirequest
import { NextRequest } from "next/server";
ninotFound
import { notFound } from "next/navigation";
niredirect
import { redirect } from "next/navigation";
nirevalidateTag
import { revalidateTag } from "next/cache";
nirevalidatePath
import { revalidatePath } from "next/cache";
niuseParams
import { useParams } from "next/navigation";
niusePathname
import { usePathname } from "next/navigation";
niuseReportWebVitals
import { useReportWebVitals } from "next/web-vitals";
niuseSearchParams
import { useSearchParams } from "next/navigation";
niuseSelectedLayoutSegment
import { useSelectedLayoutSegment } from "next/navigation";
niuseSelectedLayoutSegments
import { useSelectedLayoutSegments } from "next/navigation";