Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React useEffect fetch function

const [user, setUser] = useEffect({});

useEffect(() => {
fetch(`/api/users/${id}`)
.then(resp => resp.json())
.then(setUser);
}, []);

I was watching a tutorial and saw the above code. In the last line of useEffect, the then function is simply taking in the setUser function and NOT CALLING IT. Why isn’t the last line .then(setUser(value))?

Please help clearify this…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

this is a feature of javascript itself that doesn’t have anything to do with react itself so basically the signature of the then function take as an argument a callback (a fancy way to say a function) that means that then gets a function as argument and it give it as argument the return value of the last chain so as an example look at this :

fetch("myuserAPI").then(step1).then(step2)

const step1 = (resultOffetch) => resultOfFetch.split(" ")
const step2 = (resultOfStep1) => resultOfStep1.toUpperCase()

so here we are looking at two concepts first is chaining where you can see that we are passing one result of the first function to the function that follows and this is concept is applied here to the promise object (fetch returns a promise), also we can see that we are passing the function to the then as an argument which is another feature of javascript language that functions are first-class citizens which means that they get treated as objects you can use them as arguments, treat them as a normal object so to answer your question

.then(step1) 
is equal to
.then((previousFunctionResult) => step1(previousFunctionResult) )

and to clarify the function you shared .then(setUser(value)) here is not the right way this will call the setUserFunction immediately and you still don’t have the value variable in the scope the right way is one of theses

.then(value => setUser(value))
or
.then(setUser)

read more here chaining methods
read more here first class functions

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading