Search code examples
javascriptreactjsfetch

Looking to run a function after fetch in ReachJS


Okay, so my problem is that I'm trying to modify an array after fetching JSON and storing as an array with hooks. How would I go about doing that?

I tried using another .then and calling the function I want to call, but when logging the array to the console in the function it just gives me an "cannot read property of description undefined error" Any help? Thanks!

const [repos, setRepos] = useState([]);
const [isLoaded, setIsLoaded] = useState(false);
const [error, setError] = useState(null);

function updateDates() {
    var i;
    console.log(repos[1].description);
}

// fetch github repo sorted by updated date and store in repos
useEffect(() => {
    fetch("https://api.github.com/users/benngagne/repos?sort=updated")
    .then(res => res.json())
    .then(
        (result) => {
            setRepos(result);
            setIsLoaded(true);
        },
        
        (error) => {
            setIsLoaded(true);
            setError(error);
        }
        )
    // .then(() => {
    //     updateDates();
    // })
    }, [])

Solution

  • Updating state is asynchronous, and you are trying to access updated state data immediately after state updating function(setRepos()).

    useEffect hook is what you should be looking for. Set dependency array of useEffect to your state, so it will only work when your state changes. There, you can do your manipulations of your new state, do functions etc.

    useEffect(() => {
        if(repos){ //checking if state is not null; to not catch initial state.
        //Do your functions, calculations etc..
        }
    },[repos]);