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 or not of if 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.