Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
Issue displaying data from API

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:

Log File

Any leads would be so much helpful, thank you!! :)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda