React: Correct way to handle a component refresh on post request

hey there hopefully someone can point me in the right direction cause i’m a little confused and its been hard to find ‘best practice for handling this in react’

An Example:

I have a image being displayed via url in a react component.
the react component is getting the URL from an get request API call.
the user then updates that image by a post request replacing the previous url with a new URL.
the component will not display the updated URL, react will not re-render the page cause its not aware of the change (its not a state update) , How would I tell the component hey update now please the server db data has changed!

possible solutions I have thought of but I’m not sure if any or which is ‘correct’ or best.

using a submit button without calling e.preventdefault or
using window.locate.rerfresh() to force a page refresh .

creating a piece of state and then on success of post request overwriting the state inside the app manually.

maybe I’m overthinking this but both solutions feel kind of clumsy to me right now and would love some advice here on how others approach this

thanks!

You are supposed to store the url as a state and update the state along with the post request. Thats what state is meant for.

If you do it your post request will not even get triggered.

const Example = () => {
  const [url, setUrl] = useState("");
  useEffect(() => {
    // make a request here, then
    // if it works then
    if (checkUrlHasChanged || url !== "") {
      setUrl(theDataYouGot);
    }
  }, [url]);

  return {
    // component JSX 
  };
};

Every time url changes, the component will rerender

(edited for clarity re. @adramelech comment)

Be careful on that dependency array

It’s essentially pseudocode (although it needs to run every time the URL changes, so it has to at least include that). It can’t only be that because the mechanism for the user submitting information isn’t specified.

changing a state inside a useEffect having the same state as dependency causes infinite rerender, isn’t it ?

1 Like

Ah, I’m just assuming that there’s some logic to check inside the useEffect, edited the pseudocode

1 Like

thanks guys that helped, having a piece of state and then setting it to the response from the post is the correct method when possible. I think my overall confusion came from not utilizing context/global state it seems pretty obvious to me now xD