-1

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`
Yilmaz
  • 35,338
  • 10
  • 157
  • 202

2 Answers2

3

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: ${id}`);
  return { props: { id } };
}

Now id is passed as prop to the client:

const YourComponent=(props)=>{
   console.log("passed id prop",props.id)
}
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
2

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])
Ivan V.
  • 7,593
  • 2
  • 36
  • 53
  • I have copied this code but now I cant use this function on a button it says that updateProduct is not defined – Ghulam Mustafa Mar 05 '22 at 10:47
  • i have done something like this but it still does not work and it does not show anything `useEffect(() => { getProductById(); }, [router.query]);` – Ghulam Mustafa Mar 05 '22 at 11:06
  • try removing the update function from the useEffect and call it in useEffect and your onClick if the button –  Mar 05 '22 at 11:51