Home > Back-end >  NextJS router.query not giving the ID param
NextJS router.query not giving the ID param

Time:03-06

I am making crud using nextjs as frontend and CodeIgniter as backend I am following a tutorial where the frontend is reactjs. in reactJs when the updating part of the crud comes we can use the react-router-dom useParam function to get the ID but in nextJS we use router.query and it does not work so I am now stuck on how to get the id of the specific column to update it

 const { id } = router.query;

  const getProductById = async () => {
// if (id !== undefined && id != null && id > 0) {
  const response = await axios.get(`http://localhost:8080/companies/${id}`);
  setName(response.data.name);
  setCreatedBy(response.data.createdBy);
  console.log(id);
// }};

This is the code I am using and it gives an error that

`http://localhost:8080/companies/undefined`

CodePudding user response:

Router query can be empty on the first render, on statically optimized pages. try wrapping the code in useEffect

useEffect(()=>{
 const { id } = router.query;

  const updateProduct = async (e) => {
    e.preventDefault();
    await axios.patch(`http://localhost:8080/companies/${id}`, {
      company_name: name,
      created_by: createdBy,
    });
    router.push("/products");
  };
},[router.query])

CodePudding user response:

You can get query.id on the server-side and then pass it to the client-side

export async function getServerSideProps(context) {
  const { id } = context.query;
  console.log(`query id: ${country.name}`);
  return { props: { id } };
}

Now id is passed as prop to the client:

const YourComponent=(props)=>{
   console.log("passed id prop",props.id)
}
  • Related