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:
- Force a refresh of the whole page, which would now get the updated
nameproperty from thegetServerSidePropsfunction in the backend. - Create a copy of the props as a local state, use that to generate the UI, and update that state value whenever the
nameis updated usingfetch(). 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>;
}
- Not use
getServerSidePropsat 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!