0

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);

}

1 Answer 1

1
  • 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.
Sign up to request clarification or add additional context in comments.

3 Comments

As you mentioned above I remove async, await part from the code but then also did not give the correct result. I get an empty array. I added the edited code above.
No, I meant to put your getOnePost() and getAllOffers() into a single useEffect and make them run one by one. the async, await keywords keep them there since the await keywords make your asynchronous code run synchronously.
You can imagine like this: All useEffects are executing at the same time so they cannot get value from a cross useEffect. You will need to make your function run one after another.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.