Question About 'fetch': Can I call the same fetch function again, from elsewhere in the app?

So I have a React app. In my App component I make a fetch request to my database and retrieve some data that I use throughout my app by passing it as props. In another component, I initialize state with props when the component mounts. The user can add items to state and then when the user exits that component I send a ‘PATCH’ request with the current state and update my database. This all works fine, as in my database is being updated, until I reload the aforementioned component and my new updated data is not included, just my old data.

My hunch is that it’s because I only make a ‘GET’ request once and store that data in state in my App component so I’m reloading the same old data, despite the updates. To make it work properly I need to call the ‘get’ request again, to retrieve the new updated data.

Is my hunch correct? Is there a way to call the fetch function again without reloading the app?

(let me know if I’m not being clear. My brain is a little fuzzy from a cold.)

Hello there,

This is difficult to say, without seeing the code.

In general, your topic question’s answer is “Yes, the same fetch function can be called from elsewhere in the app”.

Without seeing your code, best I can offer is what I might have done with such an app:

const App = () => {
  const [myData, setMyData] = useState(initialData);
  const updateData = (newData) => {
    fetch('/post-data', {method: "POST", body: JSON.stringify(newData)});
  return <><OtherComponent myData={myData} updateData={updateData} /></>;

const OtherComponent = ({myData, updateData}) => {
  useEffect(() => {
    return () => { updateData(newData); } // Runs when component unmounts
  }, []);
  return <h1>{myData}</h1>

With the above, App will re-render, due to the state updating, but there is no way to update an apps state without causing it to re-render - if you did, then you would be asking React to break itself.

Hope this helps

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.