I got an issue to display my data that I fetch from an API, I don't really what is going wrong here...
I tried to use the map() function to access the data but it's not working as expected as well
import React from "react";
import axios from 'axios';
const options = {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'API_KEY'
}
};
export default class List extends React.Component {
state = {
locations: []
}
componentDidMount() {
axios.get('https://api.foursquare.com/v3/places/search?query=gallery%20&ll=48.85%2C2.35&radius=10000&categories=10004&sort=DISTANCE', options)
.then(res => {
const locations = res.data;
console.log(locations.results)
return this.setState({ locations });
})
}
render() {
return (
<div>
<ul>
<div>{this.state.locations.results}</div>
</ul>
</div>
)
}
}
I got these two errors showing up
1: Error: Objects are not valid as a React child (found: object with keys {fsq_id, categories, chains, distance, geocodes, location, name, related_places}). If you meant to render a collection of children, use an array instead
2: Unhandled Promise Rejection: Error: Objects are not valid as a React child (found: object with keys {fsq_id, categories, chains, distance, geocodes, location, name, related_places}). If you meant to render a collection of children...
This is the object that I got back in the log:
Any leads would be so much helpful, thank you!! :)
Based on the screenshot, you get back an array. React/JSX doesn't just put the array out, you need to iterate over it. Here's a snippet with functional component & a custom hook:
const { useEffect, useState } = React
const useFetchData = () => {
const [response, setResponse] = useState([])
const [loading, setLoading] = useState(false)
useEffect(() => {
setLoading(() => true)
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(json => setResponse(() => json))
.finally(setLoading(() => false))
})
return { response, loading }
}
const App = () => {
const { response, loading } = useFetchData()
return (
<div>
{
response.length && !loading
? response.map(({ id, name, username }) => {
return (
<div key={id}>{id} - {name} - {username}</div>
)
})
: "Loading users..."
}
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>
Although you used a class component in your example and this is a functional component in my snippet, the basic idea is the same: if you want to display an array of items in JSX, then you need to iterate over them with an iterator function that actually returns a JSX element.