Reputation: 1274
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}¤cies=${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>
)
}
}
Upvotes: 1
Views: 1205
Reputation: 16451
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}¤cies=${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>
Upvotes: 3