0

I am trying to set an array by reading json information from a get request. Below I hardcoded it to test and it seems to print the list in the drop-down button. But in my fetch json request It doesn't seem to work if I print from teamsList, if I print from teams(hardcoded) it works.

Here is my console output, I also noticed they look a little different on the first line even though they are both the same exact array. Is something wrong here?

console.log

let teamsList = []

    fetch(`/api/teams`)
        .then(res => res.json())
        .then(responseJSON => {
          responseJSON.map(cls => (
            teamsList.push(cls.name)
          ))
        })

    let test = ['Chaos', 'High Elves', 'Orcs']

    console.log(teamsList)
    console.log(test)

    // doesnt work
    return (
      <DropdownButton id="dropdown-team-button" title={this.props.team_name}>
          {teamsList.map(cls => (
              <div key={cls}>
                  <Dropdown.Item onClick={this.handleTeamSelection} title={cls}>{cls}</Dropdown.Item>
              </div>
          ))}
      </DropdownButton>
    )

    // works
    return (
      <DropdownButton id="dropdown-team-button" title={this.props.team_name}>
          {test.map(cls => (
              <div key={cls}>
                  <Dropdown.Item onClick={this.handleTeamSelection} title={cls}>{cls}</Dropdown.Item>
              </div>
          ))}
      </DropdownButton>
    )
Jabba the Hutt
  • 654
  • 3
  • 15
  • 3
    Fetch is an async call. Code is not waiting for teamList to be added. IT returns an empty view. – Shubham Dec 26 '19 at 06:02
  • Your `responseJSON => { ... }` function will execute 50ms or 200ms or more _later_ than everything else you wrote. This is also the reason the console looks different: Chrome infamously will display any objects asynchronously, and pull their contents as they are when Chrome gets around to doing it; so it's an empty array at one moment, but a full array some time later. The general rule is — never use results of an asynchronous callback in code that is not initiated from that callback. – Amadan Dec 26 '19 at 06:09
  • What can I use instead of fetch that is not async? – Jabba the Hutt Dec 26 '19 at 06:11
  • Its a console behaviour in javascript, when you log in the console. The value of object is evaluated on expansion and hence you see the result at that point in time. Now since fetch call it async, the value at the time of printing to th4e console was an empty array which whicch is shows before expansion. Check the duplicate for more details – Shubham Khatri Dec 26 '19 at 06:13
  • see https://stackoverflow.com/questions/54950838/how-to-use-fetch-with-async-await – Junius L Dec 26 '19 at 06:18
  • have you tried your console log stringifying the object "console.log(JSON.stringify(teamsList))" – Sachintha Nayanajith Dec 26 '19 at 06:28

0 Answers0