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
useState
is updating .. believe me. The reason why you don't see it when youconsole.log()
is becauseSetRespos
is an asynchronous function.Basically when you declare a function to update you
useState
value, react will use it as anasync
functionEXAMPLE
The output will be :
But still your
useState
will update after this. If you want to see that do this :I'm using a separate
useEffect
toconsole.log()
the value. In the[]
(dependency array) we passrespos
which simply means that theuseEffect
will run every time the value ofrespos
changes.Read more about
useStates and useEffects
in react's documentation