I am trying to get data from the backend and display it in the frontend. This is the code that I tried to do this task.
function Posts() {
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);
const buyerId=(localStorage.getItem("userId"));
console.log(buyerId);
const [offers, getOffers] = useState([]);
useEffect(()=>{
getAllOffers();
}, []);
const getAllOffers = async () => {
await axios.get(`/viewPendingSellerOffers`)
.then ((response)=>{
const allNotes=response.data.existingOffers;
getOffers(allNotes);
})
.catch(error=>console.error(`Error: ${error}`));
}
console.log(offers);
const wasteItem = offers?.filter(wasteItem => wasteItem.status==='accepted' && wasteItem.buyerId===buyerId && wasteItem.wasteItemsListId==='completePost');
console.log(wasteItem);
return(
<main className="grid-b">
{notes.map((note,index)=> {
if(wasteItem.find(o=>o.postId !== note._id) !== undefined)
return (
<article>
<div className="text-b">
<h3>Post ID: {index + 1}</h3>
<p>Location: {note.address}</p>
<p>Post Type: {note.postType}</p>
<p>Address: {note.address}</p>
<p>Telephone No: {note.contact}</p>
</div>
</article>
);
})}
</main>
);
}
export default Posts;
I call the first API and get a length 7 array of objects. This is an image of this array.
Then I call the second API and get a length 6 array of objects. This is an image of this array.
Then I try filter function to results of second API call const wasteItem = offers?.filter(wasteItem => wasteItem.status==='accepted' && wasteItem.buyerId===buyerId && wasteItem.wasteItemsListId==='completePost'); and get length 2 array of objects.
Then I try to map the results using the map function. In the map function, I want only to map 5 items according to the above results. It means first API call I get 7 objects and through the filter function, I get 2 objects so I want to remove those 2 objects data from the mapping. To do this I add the if condition like this if(wasteItem.find(o=>o.postId !== note._id) !== undefined). But it mapping all the 7 items that are in the results of first API call. When I change if condition like this if(wasteItem.find(o=>o.postId === note._id) !== undefined) it maps 2 items that get from the above filter function. How do I solve this problem and map only 5 items?


