J
J
jedifa2021-08-01 01:15:52
React
jedifa, 2021-08-01 01:15:52

How to add dynamic id in NextJS getServerSideProps?

Please tell me I have a component

export default function Home() {
  const [id, setId] = useState(0);
  const changeId = () => {
    setId(id + 1);
  }
  return (
    <div>
       <button onClick={() => changeId()}>Click</button>
   </div>
  )
}

I need to get data from the server, I get it via getServerSideProps:
export async function getServerSideProps(context) {
  const res = await fetch(`https://example/:id`); //Вместо :id должен быть id который в компоненте home
  const data = await res.json();

  return {
    props: {data}
  }
}

And after clicking on the button, when the state id changes, I need to get new data by another id. Please tell me how to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valery, 2021-08-03
@jedifa

Directly in the component <Home />:

useEffect(() => await fetch(`https://example/${id}`), id)

in getServerSidePropsyou can use the standard id to preload the desired content, but then drive from the component.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question