DJ2
DJ2

Reputation: 1751

Mapping over array of objects - unable to get values into dropdown

The title pretty much explains my issue. I mocked up some data I need to display in a dropdown, the dropdown component is from SUIR

mock.onGet("/slotIds").reply(200, {
  data: {
    slotIds: [{ id: 1 }, { id: 2 }, { id: 3 }]
  }
});

I'm updating state with the fetch of the data

  const { data } = await axios.get("/slotIds");
  console.log("Slot IDs --> ", data);
  const slotIds = data.data;
  this.setState({ slotIds: slotIds });
  console.log(this.state.slotIds);
  //the above log outputs [Object, Object, Object] so slotIds is in fact an array

Then I'm mapping over that values to render the id in a dropdown

        options={slotIds.map(id => {
          return {
            key: id.id,
            text: id.id,
            value: id.id
          };
        })}

Can't quite get it to work, am I mapping the values incorrectly or returning the wrong values?

I have a codesandbox that reproduces the issue. You will need to click on the the Login button at the top of the splash page. Select the Slot Sec Officer radio button, look at the console it will show the successful api call and how the slotIds state is updated. I have commented out the .map function because it is causing the component not rendering when Slot Sec Officer option is chosen.

The entire Login code is inside /components/Login.js. The class SlotSecIdInputs contains the api call and the actual <Dropdown> component that has the map function.

Upvotes: 0

Views: 49

Answers (1)

The Reason
The Reason

Reputation: 7973

You have a couple of mistakes in a SlotSecIdInputs:

  1. You haven't defined your state slotIds in a constructor
  2. The default state should be defined as an array, cuz you mapping over fetched items which later stored as an array
  3. You should control the fetch loading.

Initially when the component is just rendered you don't have slotIds state, so you cant map over it and you get an error. After you fetched slotIds you should make sure it's not empty and after it do mapping over it.

Hope it will help you.

Upvotes: 1

Related Questions