Pretty much what it says on the title. When I console.log(repos) it returns an empty array. Why is the repos state not updating?
import React, { useEffect, useState } from "react";
import axios from "axios";
export default () => {
const [repos, setRepos] = useState([]);
useEffect(() => {
(async () => {
try {
let repo_lists = await axios.get(
"https://api.github.com/users/Coddielam/repos"
// { params: { sort: "created" } }
);
setRepos(repo_lists.data.slice(1).slice(-10));
console.log(repo_lists.data.slice(1).slice(-10));
console.log(repos);
} catch (err) {
setRepos([
"Something went wrong while fetching GitHub Api./nPlease use the link below to view my git repos instead ",
]);
}
})();
}, []);
return (
<div className="content">
<h2>View my recent git repos:</h2>
<ul>
...
</ul>
</div>
);
};
Answer is very simple. Your
useStateis updating .. believe me. The reason why you don't see it when youconsole.log()is becauseSetResposis an asynchronous function.Basically when you declare a function to update you
useStatevalue, react will use it as anasyncfunctionEXAMPLE
The output will be :
But still your
useStatewill update after this. If you want to see that do this :I'm using a separate
useEffecttoconsole.log()the value. In the[](dependency array) we passresposwhich simply means that theuseEffectwill run every time the value ofresposchanges.Read more about
useStates and useEffectsin react's documentation