Home > Net >  TypeError: X.map is not a function (fetching api into an object not into an array)
TypeError: X.map is not a function (fetching api into an object not into an array)

Time:04-09

new to Reactjs! I fetch an api (using axios) and then try to map thought it but i cannot because its an object. How can i fix this! how can i get specific data of that object ? I wanna fetch the names of the memes.
if i use another API like this one ex." https://www.breakingbadapi.com/api/" and use an extra path ( / ) in html like this
ex. https://www.breakingbadapi.com/api/**characters** i get an array and i get the job done.

Why the same ex. as above doesnt work with my case?

!The Error that i get is memes.map is not a function!

Here is my code:

import React, { useState, useEffect } from "react";
import axios from "axios";
import { Header } from "./components/Header";
import Memes from "./components/Memes";
import "./App.css";

const App = () => {
  const [memes, setMemes] = useState({});
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchItems = async () => {
      const result = await axios("https://api.imgflip.com/get_memes");
      console.log(result.data);

      setMemes(result.data);
      setIsLoading(false);
    };
    fetchItems();
  }, {});

  return (
    <div className="App">
      <Header />
      <Memes isLoading={isLoading} memes={memes} />
    </div>
  );
};

export default App;




import React from "react";
const Memes = ({ isLoading, memes }) => {
  return isLoading ? (
    <h1>Loading</h1>
  ) : (
    <section>
      {memes.map((meme) => (
        <h1 key={meme.char_id}>{meme.name}</h1>
      ))}
    </section>
  );
};

export default Memes;

CodePudding user response:

wrong code : const [memes, setMemes] = useState({});

update code :const [memes, setMemes] = useState([]);

CodePudding user response:

On First render memes value will be null ( sync code rendering ). Please try the following

{memes?.map((meme) => (
        <h1 key={meme.char_id}>{meme.name}</h1>
))}

? will make sure to run map once the meme array is populated with data.

Also, useState should have [] as init value like:

const [meme, setMeme] = useState([])
  • Related