const [user, setUser] = useState([]);
useEffect(() => {
fetch("https://reqres.in/api/users?page=2")
.then((res) => res.json())
.then(setUser);
return () => {
console.log("CleanUp Code");
};
}, []);
How the set State is automatiocally set with this method .then(setUser); --> How the state is set with this method any explanation
.then is designed so that you pass a function into it. When the promise resolves, your function will be called and will be passed in the value that the promise resolved to.
So for example, you can create a brand new function, such as (res) => res.json(), and pass that function in to be called when the promise resolves. Or you can pass in a function which already exists, such as setUser. And again, that function will be called when the promise resolves. Calling setUser sets the state.
const [user, setUser] = useState([]);
useEffect(() => {
fetch("https://reqres.in/api/users?page=2")
.then((res) => setUser(res.data))
.catch(err=>res.json(message: err.message));
return () => {
console.log("CleanUp Code");
};
}, []);
const [user, setUser] = useState([]);
useEffect(() => {
fetch("https://reqres.in/api/users?page=2")
.then((res) => res.json())
.then((res) => setUser(res.data))
.then(setUser);
return () => {
console.log("CleanUp Code");
};}, [])