0

It will continuously showing this error that TypeError: post.map is not a function. please give me some appropriate answer guyz.

import React from "react";
import { useState } from "react";

function LoopThrough() {
const [post, setpost] = useState("");

function getDataFromApi() {
  // using axios method

  axios
    .get("https://jsonplaceholder.typicode.com/posts")
    .then((get) => {
      console.log(get.data);

      setpost(get.data);
    })
    .catch((error) => {
      console.log(error);
    });
}

const getdatafromjson = post.map((myobj) => {
  return (
    <div>
      <h2>{myobj.title}</h2>
    </div>
  );
});

return (
  <>
    <h2>Return Html using http methods</h2>

    <button onClick={getDataFromApi}>Get Data</button>

    {getdatafromjson}
  </>
);
}
export default LoopThrough;

Note : In this example , i want to get data from external Api using Axios method(language: React JS) and render it onto the display using react hooks and map() method but it doesnt work.

Error : TypeError: post.map() is not a function .

2
  • Your state starts off as a string, so you're trying to do .map() on a string. Your response to your API call doesn't come back until sometime later after your initial render Commented Dec 26, 2021 at 5:20
  • What you can do to solve this problem is set the initial value of the post as [ ]. const [post, setpost] = useState([ ]); What this will do is to allow the map function to be available until the response from the API is set because initially, you are using empty string as a value. And strings don;t have map(). And as mentioned by @NickParsons, Your response to your API call doesn't come back until sometime later after your initial render. Cheers. Commented Dec 26, 2021 at 6:40

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.