Search code examples
javascriptreactjsreact-hookssetstate

React SetState in event handler behaves differently with data mocked and data from API


I have am reproducing exactly the same case ( same code ) between two scenarios.

  1. With data mocked
  2. With data requesting from an API

1) Case with Data Mocked => https://codesandbox.io/s/select-demo-0e90s works as expected

The data mocked is the following

const [items] = React.useState([
  { id: "1", name: "First Element" },
  { id: "2", name: "Second Element" },
  { id: "3", name: "Third Element" }
]);

setSelectedName(item.name) => returns the item name correctly

2) Case with API Request ( To allow the the request CORS plugin Chrome extension has to activated ) => https://codesandbox.io/s/select-demo-71u7h

The data is coming from a call request in action/index.js => fetchLeaguesList()

In the League.js component

setSelectedLeagueName(item.name) => TypeError Cannot read property 'name' of undefined, item in this case is undefined

So my question is why item is undefined in my second case? How can i fix it in this scenario?


Solution

  • This is because inside League.js on line 19 you do const item = items.find(item => item.id === value);

    But the JSON model that comes back from the API is not formed with the id property, but rather league_id.

    You should then change the line to const item = items.find(item => item.league_id == value);