Search code examples
javascriptreactjsbootstrap-4fetch-api

Javascript React app "fetch" returning 'undefined' on reload from browser, but returning data when reloading from API


I have a component that pulls a json object from github

async function getQueryJson(URL) {
  await fetch(URL) // This gets the git commits
    .then((res) => res.json()) //Converts it to a JSON
    .then(
      (result) => {
        setCommits(result) // This puts the JSON containing the commits made to gitlocale into state
        console.log('Outputting value of GQJ')
        console.log(commits)
      },
      (error) => {
        console.log('Error in fetch: ' + error)
      },
    )
}

which is called within the UseEffect portion of my React code to populate a State with an array of JSON objects.

useEffect(() => {
  var userObject = {}
  getQueryJson(githubCommits)
})

My issue is that when I first refresh the page, the the "commits" returns as "undefined" - if I change my code in my IDE which reloads the page, the "commits" returns an array of JSON and the code executes properly.

To complicate matters further, if I output (res.json()) to the console, I receive the JSON object in all circumstances regardless of whether my state is set to undefined, which makes me nervous about the execution.

Am I correctly using the async fetch function?
I don't think I need to perform this twice. It has the json object,but on a first visit it does not process the json.

I have removed the async/await portion, which did not affect functionality. I have moved the results to another state, which receives the undefined/json object the same, so it's not being incidentally initialized multiple times I have attempted to pull the JSON independently from the fetch, which didn't work.


Solution

  • You are trying to console.log(commits) right after it is set. Unlike regular variables, states are not set instantly. If you want to make an operation on the commits state when it ACTUALLY changes, it is better to use a hook like useEffect to trigger when commits is set.

    // Ex:
    useEffect (() => {
      // your code
    }, [commits]);