1

I have getServerSideProps function to get data from API:

export async function getServerSideProps() {
  const res = await fetch(
    `https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${queryCocktailName}`
  )
  const data = await res.json()
  return {
    props: { data },
  }
}

I need to get query in this function, ( /search/queryCocktailName/ ) i tried const {query} = useRouter() but as NextJS say: Hooks can only be called inside of the body of a function component

This component location: search/[id].tsx

Denis
  • 65
  • 2
  • 7

2 Answers2

0

This should work:

import { GetServerSidePropsContext } from "next";

export async function getServerSideProps({
  params
}: GetServerSidePropsContext<{ id: string }>) {
  const res = await fetch(
    `https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${params?.id}`
  );
  const data = await res.json();
  return {
    props: { data }
  };
}

See docs. getServerSideProps gets context object as a first parameter and it contains params field which should contain an id field, because your file is named [id].tsx.

Edit: changed to TypeScript version.

paolostyle
  • 1,849
  • 14
  • 17
0

Every getServerSideProps have context, which comprises of req and res.

export async function getServerSideProps({req, res}) {
  const { url = "" } = req || {};
  //url will have the query of your route like :: url =  /search/queryCocktailName/

  const res = await fetch(
    `https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${queryCocktailName}`
  )
  const data = await res.json()
  return {
    props: { data },
  }
}

Above code will work for your use-case

abhikumar22
  • 1,764
  • 2
  • 11
  • 24