John White
John White

Reputation: 131

Calling a variable from fetch into React render function

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.

Upvotes: 0

Views: 382

Answers (2)

Turan
Turan

Reputation: 302

Your const microVit is encapsulated.

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

Upvotes: 1

Roy Wang
Roy Wang

Reputation: 11260

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(...

Upvotes: 1

Related Questions