How to repopulate data when using getServerSideProps and the page allows data modification in NextJS

Viewed 52

Lets say I have a page example.com/user/1 that consists of a single component which I pass props to using getServerSideProps and thus is SSR'd. For this example lets say the props is {"name":"Bob"}

That page allows the user to modify the name value that is displayed on that page, which is updated using a standard fetch() call to the backend. That fetch() call returns the updated value (lets say {"name":"Alice"}), which I now would like to display on the UI.

However I can't because the component is using the props to generate the UI.

As I see it I have 3 options:

  1. Force a refresh of the whole page, which would now get the updated name property from the getServerSideProps function in the backend.
  2. Create a copy of the props as a local state, use that to generate the UI, and update that state value whenever the name is updated using fetch(). So something like:
const User = ({ name }) => {
  const [localName, setLocalName] = useState(``);
  useEffect(() => {
    setLocalName(name);
  }, []);

  const saveNewName = async (name) => {
    await fetch(url, {name}, etc....);
    setLocalName(name);
  }

  // Still missing the UI to enter a new name and save it to the backend!

  return <p>Hello, {localName}</p>;
}
  1. Not use getServerSideProps at all, nor the component props, but instead fetch the data after the page is hydrated, like a "traditional" SPA.

Are these three approaches reasonable? Which is the better option? Is there another, better option? Thank you!

1 Answers

You can use getServerSideProps to fetch data at request time and then have as state which get updated when the data has been changed --option 2

alternatively, you can use client side if you don’t need to pre-render the data, SWR is an option that handles caching, revalidation, focus tracking, refetching on intervals, and more. Check SWR by NextJS

Related