Yevhen Kuzmenko
Yevhen Kuzmenko

Reputation: 810

How to access array in array from react component?

I have this array:

{
  "firstname": "Jessica",
  "lastname": "Wood",
  "favorite": {
        "movie": Flint Town,
        "drink": Sprite
  }
}

I am trying to get drink and i got Objects are not valid as a React child found: object with keys.

How can i fix that?

My react component:

import React, { Component } from 'react';
import axios from 'axios';

class Home extends Component {

  state = {
    info: []
  }

  componentDidMount() {
    axios.get('http://localhost:9000/api')
      .then(res => {
        const info = res.data;
        this.setState({ info });
      })
  }

  render() {
    return (
      <ul>
        <li>{this.state.info.favorite.drink}</li>
      </ul>
    )
  }
}
export default Home;

Upvotes: 2

Views: 2835

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

You need to parse the values inside the "favorite" object so that they can be rendered as strings.

It also looks like you're trying to access a prop in this.state.info before it exists. Which is why it gives you the undefined error. The render method runs before you assigned anything to info, which you did in componentDidMount().

To workaround this, we can have a loading-state value to determine what to show. The loading-state will toggle after your componentDidMount() logic has completed, ensuring your state has populated.

Here's the sandbox: https://codesandbox.io/s/bold-germain-k3f23

class Home extends Component {
  state = {
    info: {},
    loading: true
  };

  componentDidMount() {
    axios.get("http://localhost:9000//").then(res => {
      const info = res.data;
      const parsedInfo = {
        ...info,
        favorite: Object.entries(info.favorite).reduce((obj, [k, v]) => {
          obj[k] = "" + v;
          return obj;
        }, {})
      };

      this.setState({ info: parsedInfo, loading: false });
    });
  }

  render() {
    const { loading, info } = this.state;
    if (loading) {
      return <div>Loading</div>;
    } else {
      return (
        <div>
          <div>{info.favorite.movie}</div>
          <div>{info.favorite.drink}</div>
        </div>
      );
    }
  }
}

Upvotes: 2

Related Questions