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

246
Visualizações
apidata.map is not a function : ReactJS

Can someone please tell me why i am getting this error . I tried fixing it all day, but I could not fix it. So at last i had to come at stackoverflow

This is my code : App.js

import "./App.css";

function App() {
  const [inputvalue, setInputvalue] = useState(" ");
  const [apidata, setApidata] = useState([]);
  const [finalpoint, setFinalpoint] = useState("");
  useEffect(() => {
    fetch(
      `https://weatherapi-com.p.rapidapi.com/forecast.json?q=+${inputvalue}&days=3`,
      {
        method: "GET",
        headers: {
          "x-rapidapi-host": "weatherapi-com.p.rapidapi.com",
          "x-rapidapi-key":
            "7f89bf16ebmsh9dff0f23f963d34p190691jsn264543e18108",
        },
      }
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setApidata(data);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [finalpoint]);

  const onchangeinput = (e) => {
    setInputvalue(e.target.value);
  };

  const onsubmithandler = (e) => {
    e.preventDefault();
    setFinalpoint(inputvalue); 
  };

  return (
    <div className="App">
      <div className="main">
        <h2>Welcome To weather App </h2>
      </div>

      <form onSubmit={onsubmithandler}>
        <input type="text" value={inputvalue} onChange={onchangeinput} />
        <button type="submit">Search</button>
      </form>
      {apidata.map((data, i) => {
        return <h1>{data.current.feelslike_c}</h1>;
      })}
    </div>
    //Map
  );
}

export default App;

This is the error I am getting : enter image description here

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

0

Check if you are receiving undefined here:

.then((data) => {
   setApidata(data);
 })

and overriding the state with undefined.

about 4 years ago · Juan Pablo Isaza Relatório

0

What I'm seeing is the api is initially returning an error object. Also, when the proper data is returned, it comes back as an object. When setting your state, you will have to set data inside of an array (if you want to use the map method). You will also have to handle the error by doing something like this:

import { useState, useEffect } from "react";

function App() {
  const [inputvalue, setInputvalue] = useState(" ");
  const [apidata, setApidata] = useState([]);
  const [finalpoint, setFinalpoint] = useState("");
  useEffect(() => {
    fetch(
      `https://weatherapi-com.p.rapidapi.com/forecast.json?q=+${inputvalue}&days=3`,
      {
        method: "GET",
        headers: {
          "x-rapidapi-host": "weatherapi-com.p.rapidapi.com",
          "x-rapidapi-key": "7f89bf16ebmsh9dff0f23f963d34p190691jsn264543e18108"
        }
      }
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data)
        if (data.error) return null;
        setApidata([data]);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [finalpoint]);

  const onchangeinput = (e) => {
    setInputvalue(e.target.value);
  };

  const onsubmithandler = (e) => {
    e.preventDefault();
    setFinalpoint(inputvalue);
  };

  console.log("test", apidata);


  return (
    <div className="App">
      <div className="main">
        <h2>Welcome To weather App </h2>
      </div>

      <form onSubmit={onsubmithandler}>
        <input type="text" value={inputvalue} onChange={onchangeinput} />
        <button type="submit">Search</button>
      </form>
      {apidata.length
        ? apidata.map((data, i) => {
            return <h1 key={i}>{data.current.feelslike_c}</h1>;
          })
        : null}
    </div>
    //Map
  );
}

see working example: https://codesandbox.io/s/eager-wind-06ywo?file=/src/App.js

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