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

1
  • 2
    The function is being called - the .then function accepts a callback function as parameter. With this notation, the callback function is invoked with the parameter of the promise, in this case, the user object that is returned from the API call. Normally, the .then block would accept a parameter of type (userData: any) => void - which your setUser function complies with. So .then(setUser) is (almost) synonymous to .then(value => setUser(value)) Commented Sep 21, 2022 at 9:10

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.