Reputation: 33
I am new to react and I try to get an array of data from the backend and display it in the component. This is the code I wrote for that.
const [notes, getNotes] = useState('');
useEffect(()=>{
getAllNotes();
}, []);
const getAllNotes = async () => {
await axios.get(`/buyerPosts`)
.then ((response)=>{
const allNotes=response.data.existingPosts;
getNotes(allNotes);
}
)
.catch(error=>console.error(`Error: ${error}`)
);
}
console.log(notes);
The map function is this:
{notes.map((notes,index)=>(
<article>
<div className="text-b">
<h3>Post ID: {index+1}</h3>
<p>Location: {notes.address}
</p>
</div>
</article>
)
)
}
But then I get an error like this: TypeError: notes.map is not a function
How do I solve this issue?
Upvotes: 0
Views: 736
Reputation: 5912
You should set initial values to empty array.
const [notes, getNotes] = useState([]);
make sure your type is array before updating. also for safer side do null checks.
{notes?.map((notes,index)=>(
<article>
<div className="text-b">
<h3>Post ID: {index+1}</h3>
<p>Location: {notes.address}
</p>
</div>
</article>
)
)
}
Upvotes: 1