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

365
Visualizações
JavaScript's map() method is failing with the error "map is not a function"

I am trying to get out a list of items from the array from an API but when I use the map function on items it says the map is not a function.

import React from 'react'
import { useState } from 'react';
const axios = require('axios');

const Api = () => {

const [items, setItems] = useState([]);

   const getUser = async () => {
        try {
          const response = await axios.get('http://localhost:5000/api/products');
          console.log(response);
          setItems (JSON.stringify(response));
        } catch (error) {
          console.error(error);
        }
      
}

return (
    <div>
        <button onClick={getUser}> Fetch Data</button>
        <br />
        <br />
        <br />
        {items}
    </div>
)

}

export default Api
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You shouldn't use JSON.stringify. since it's already object

Just change it to below code


  const response = await axios.get('http://localhost:5000/api/products');
  setItems(response.data);
about 4 years ago · Juan Pablo Isaza Relatório

0

axios.get() method returns the object and you can't use the map() method on an object as it's been defined on the prototype of an array. You can find more details of Array.prototype.map() here

First of all, let's understand what axios.get() method returns.

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the HTTP headers that the server responded with
  // All header names are lower cased and can be accessed using the bracket notation.
  // Example: `response.headers['content-type']`
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

You can find more details here. That means the actual data you are looking for resides in response.data. You need to extract it.

const { data } = response;

Now you need to analyze and process the data into the React renderable format.

about 4 years ago · Juan Pablo Isaza Relatório

0

It worked by setItems(response.data)

import React from 'react'
import { useState } from 'react';
const axios = require('axios');

const Api = () => {

const [items, setItems] = useState([]);

   const getItems = async () => {
        try {
          const response = await axios.get('http://localhost:5000/api/products');
          console.log(response.data);
          
          setItems (response.data);
         
          console.log(response.data)
        } catch (error) {
          console.error(error);
        }
        
}

return (
    <div>
        <button onClick={getItems}> Fetch Data</button>
        <br />
        <br />
        <br />
       
        {items.map((item)=>(
            <div >
                <h1>{item.name}</h1>
                <h2>{item.price}</h2>
            </div>
        ))}


    </div>
)

}

export default Api
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