0

I'm mapping over an array of vitamins from json, and I want to return the name of each Vitamin in the array in a dropdown menu when clicked on.

I thought I could declare a const variable in the fetch function, and use that in my JSX.

  componentDidMount() {
    fetch('/users')
    .then(res => res.json())
    .then(micros => micros.vitamins.map((micro) => {
      const microVit = micro;
    }))
  }

  render() {
    return (
     <form>
        <label className="nutrient-label">
          Vitamins
        </label>
       <select value={this.props.value} onChange={this.handleChange}>
         <option value="" selected>--Vitamins--</option>
         {microVit.map((vitamin, index) =>
           <option value={vitamin.value} key={index}>{vitamin.name}</option>
         )}
       </select>
    </form>
   )
  }

When I console.log(microVit) in the fetch function, I do get the array of Vitamins. It just doesn't carry over to the map function I'm trying to work in the return statement of my render function.

2 Answers 2

1

You need to store it in the state and update it via setState to re-render the component with the new data:

class ... {
  state = { microVit: [] }

  componentDidMount() {
    ...
    .then(({ vitamins }) => this.setState({ microVit: vitamins })
  }

  render() {
    ...
      {this.state.microVit.map(...
Sign up to request clarification or add additional context in comments.

Comments

1

Your const microVit is encapsulated.

Move the decleration to outside your component did mount method ideally to internal state or a redux store.

Comments

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.