Search code examples
mysqlreactjscodeigniternext.jsnext-router

NextJS router.query not giving the ID param


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`

Solution

  • 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)
    }