Home > Mobile >  React useEffect fetch function
React useEffect fetch function

Time:09-21

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

CodePudding user response:

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

  • Related