0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow I can't believe I missed your first/second point. Lots of similar variable names and I just missed it. What do you mean by control the fetch loading?
The slotId dropdown when selected is updating the value to formik state but it's not reflected in the actual dropdown itself

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.