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.
.map()on a string. Your response to your API call doesn't come back until sometime later after your initial renderpostas[ ].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 usingemptystring 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.