Harshana
Harshana

Reputation: 35

Get an empty array when use array of objects in filter function React

I am new to react and try to get data from the database and view data in frontend. This is the code I tried.

function ViewPost() {

    const { postId } = useParams();
    console.log(postId);

    const [post, setPost] = useState({});

    useEffect(()=>{
        getOnePost();
    }, []);

    useEffect(()=>{
        if (post && post.location) {
            console.log(post.location);
            console.log(post.location.longitude);
            console.log(post.location.latitude);
        }
    }, [post]);

    const getOnePost = async () => {
        try {
            const response = await axios.get(`/buyerGetOnePost/${postId}`)
            console.log(response);
            const allPost=response.data.onePost;
            setPost(allPost);
        } catch (error) {
            console.error(`Error: ${error}`)
        }
    }
    console.log(post);

    console.log(post.wasteItemList);

    const [offers, setOffers] = useState([]);

    useEffect(()=>{
        getAllOffers();
    }, []);

    const getAllOffers = async () => {
        await axios.get(`/viewPendingSellerOffers`)
            .then ((response)=>{
                const allNotes=response.data.existingOffers;
                setOffers(allNotes);
            })
            .catch(error=>console.error(`Error: ${error}`));
    }
    console.log(offers);

    const wasteItem = offers?.filter(wasteItems => wasteItems.status==='accepted' && wasteItems.wasteItemsListId===post?.wasteItemList?._id);
    console.log(wasteItem);
}

When I call the first API I get these results. This is an image of results.

First API call results

In the above image, there is a length 2 array of objects called as wasteItemList. Then I call the second API and get these results.

Second API call results

This image shows length 8 array of objects. Then I try to filter the data of these two arrays using this const wasteItem = offers?.filter(wasteItems => wasteItems.status === 'accepted' && wasteItems.wasteItemsListId === post?.wasteItemList?._id); code. But I get a length 0 empty array as the results of this filter function. But when I try an ID of a wasteItemList array 6112679258125b0418844368 instead of using this post?.wasteItemList?._id code I get the correct result. What is the problem here? How do I solve this problem?

Edited code:

function ViewPost() {

    const { postId } = useParams();
    const [post, setPost] = useState(undefined);
    const [offers, setOffers] = useState(undefined);
    useEffect(() => {
        setPost(undefined);
        axios
            .get(`/buyerGetOnePost/${postId}`)
            .then((resp) => setPost(resp.data.onePost))
            .catch((err) => console.error(err));
    }, [postId]);
    useEffect(() => {
        axios
            .get(`/viewPendingSellerOffers`)
            .then((response) => setOffers(response.data.existingOffers))
            .catch((err) => console.error(err));
    }, []);

    useEffect(()=>{
        if (post && post.location) {
            console.log(post.location);
            console.log(post.location.longitude);
            console.log(post.location.latitude);
        }
    }, [post]);

    console.log(post);
    console.log(post?.wasteItemList);
    console.log(offers);

    const wasteItem = offers?.filter(wasteItems => wasteItems.status==='accepted' && wasteItems.wasteItemsListId===post?.wasteItemList?._id);
    console.log(wasteItem);

}

Upvotes: 0

Views: 123

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

  • useEffect runs asynchronously so your post will not be available on your getAllOffers function which is located in your second useEffect.
  • You will need to make your getOnePost() and getAllOffers() to run synchronously within a single useEffect.
  • Or the problem is in your condition checks as I can't tell much only by your given array picture.

Upvotes: 1

Related Questions