I have a React application, in which I need:
- Set the initial state
- Create an object, if the initial object doesn’t exists
- Update the created object
- Get the updated object
I want to do this with custom hooks and local state. For now I don’t want to use Redux or other state-centrilized solutions
I am a bit confused, because I haven’t been working with React for some time and I forget the concept a bit… I wanted to split the code from one huge piece of code inside one useEffect and use a custom a hook per one rest request plus some logic aroud this.
This is not my real code, but it’s quit close to it.
This is my main component.
function MyApp() {
const [myState, setMyState] = useState(myInitialObject);
// hook where I create a new object via post request
const { newObject } = useCreateMyNewObject(myState);
// hook where I update the created object via put request, I dont need the result
useUpdateMyNewObject(newObject);
// hook where I call get method
const updatedObject = useFetch(newObject);
return (
<>
{ use properties of updatedObject }
</>
);
}
It calls post method twice, put – ones and get – never.
We use strict mode, and I guess this is why post method is called twice, but I have no idea why get (useFetch hook) doesn’t work.
This is not real code of the useFetch hook:
const useFetch = (myInitialObject) => {
const [myState, setMyState] = useState(myInitialObject);
useEffect(() => {
if (!myState?.id) {
return;
}
async function fetchFromServer(id) {
const fetchedObject = await fetchObject(id);
setMyState(fetchedObject );
}
fetchFromServer(myState.id)
}, [myState]);
return myState;
};
My question is what do I do wrong?
2
There’s no way for useFetch
to wait until the PUT has completed. What’s likely happening:
- POST creates object
- newObject probably starts out null and becomes something as a result of POST
useUpdateMyNewObject
anduseFetch
kick off at essentially the same time, with the initial null value, and do nothing, then maybe again with the updated value. Seems likeuseFetch
must be short-circuiting, suggestingnewObject
isn’t getting updated as you expect.
At the very least, I think you need to await the PUT before calling useFetch. Checking (printing to console or watching in the debugger) on the values of newObject
between the various calls will likely be helpful.