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
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
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.
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