1

I'm making a application using React.js. I fetch some data using API and I'm trying to show that data in a list. Currently I receive the following error when I tried to iterate through the data.

Objects are not valid as a React child (found: object with keys {USDUSD, USDEUR, USDCAD, USDAUD}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Exchange

Even though I store the data in array, this error appears.

I checked that there is a similar thread related this error : Objects are not valid as a React child, but these answer does not help my case.

Here is my code.

import React from 'react';
import axios from 'axios';

const baseUrl = 'http://apilayer.net/api/historical?'
const API_KEY = 'API_KEY'
const date = '2017-10-22';
const currencies = 'USD,EUR,CAD,AUD';
const format = 1;


export default class Exchange extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        item : []
    };
}

componentDidMount(){
const url = `${baseUrl}${API_KEY}&date=${date}&currencies=${currencies}&format=${format}`
axios.get(url)
     .then(({data}) => {
        this.state.item.push(data.quotes);
        this.setState({
            item: this.state.item
        });
     })
     .catch((err) => {})
 console.log("item" + this.state.item)
 }

render() {
const rate = this.state.item.map((element, index)=>{
   console.log("element" + element)
return <div key={index}>
        <p>{element}</p>
        </div>
 }); 

    return (
        <div>
        <div>Exchange</div>
        <ul>Today's rate
        <li>{ rate }</li>
        </ul>
       </div>
        )
    }
 }
8
  • element is properly not a string, number or array.. Commented Oct 25, 2017 at 14:55
  • what does console.log('element', element) return ? Commented Oct 25, 2017 at 14:59
  • yes, you are right. Mistakenly I pasted it so I edit the code now. Still I receive the same error. Commented Oct 25, 2017 at 14:59
  • @ChaseDeAnda It returns element[object Object] Commented Oct 25, 2017 at 15:00
  • 1
    Okay yeah so that won't work. You need to use the data from that object to render the items. What data is in the object? In your componentDidMount, what is data.quotes? Commented Oct 25, 2017 at 15:00

1 Answer 1

3

Since each quote is an object, you can use Object.keys() to loop through the object in the .map() to display each value.

const baseUrl = 'http://apilayer.net/api/historical?'
const API_KEY = 'API_KEY'
const date = '2017-10-22';
const currencies = 'USD,EUR,CAD,AUD';
const format = 1;
const quotes = {
  USDUSD: 1,
  USDEUR: 0.850499,
  USDCAD: 1.26377,
  USDAUD: 1.280799
};

class Exchange extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      item: []
    };
  }

  componentDidMount() {
    //const url = `${baseUrl}${API_KEY}&date=${date}&currencies=${currencies}&format=${format}`
    //axios.get(url)
    //.then(({data}) => {
    this.setState({
      item: this.state.item.concat([quotes])
    });
    //})
    //.catch((err) => {})
    //console.log("item" + this.state.item)
  }

  render() {
    const rate = this.state.item.map((quotes, index) => {
      return Object.keys(quotes).map(key => {
        return (
            <div key = {key} >
              <p>{quotes[key]}</p>
            </div>
          )
      })
    });

    return ( 
      <div>
        <div>Exchange</div> 
        <ul> 
          Today 's rate
          <li> {rate} </li> 
        </ul>
     < /div>
    )
  }
}

ReactDOM.render( < Exchange / > , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

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

2 Comments

Thank you so much for the answer with a code snippet. It worked with my project perfectly. I didn't know about object.key().
Awesome glad you got it working! In the future we'll also have Object.values(obj) which will return an array of all the values, pretty sweet!

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.