React : Cannot fetch data if multiple conditions on API

I'm going insane over this one. The api data is returning correctly when using postman, but for some reason in React I cannot get the data. While experimenting I noticed that if I pass only one condition in the api I will get the response back in React, but when passing two I cannot. Keep in mind this is only happening in react, so the API in postman is returning the response perfectly.

React Snippet:

  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

      useEffect(() => {
        const fetchData = async () => {
          try {
            const { data: response } = await axios.get('/api/activity/suggested');
            setData(response);
          } catch (error) {
            console.error(error);
          }
          setLoading(false);
        };
    
        fetchData();
      }, []);

Mongoose api :

    router.get('/suggested', auth, async (req, res) => {
      try {
        const user = await User.findById(req.user.id);
    
        const activity = await Activity.find({
          event: 'suggest_to_user',
          user: req.user.id,
        })
          .sort({ date: -1 })
          .populate([
            {
              path: 'user',
            },
            {
              path: 'ref_following',
            },
            {
              path: 'ref_request',
            },
            {
              path: 'ref_review',
              populate: [
                {
                  path: 'suggestion',
                },
              ],
            },
            {
              path: 'ref_collection',
              populate: [
                {
                  path: 'user',
                },
              ],
            },
            {
              path: 'ref_suggestion',
            },
          ]);
    
        res.json(activity);
      } catch (error) {
        console.error(error.message);
        res.status(500).send('Server Error');
      }

});

Removing a condition here make it work in React:

 const activity = await Activity.find({
          event: 'suggest_to_user',
          user: req.user.id,
        }) 

1 answer

  • answered 2022-01-23 04:05 Abu Sayad Hussain

    I think the problem is that when you call the API from your to react app. It doesn't find the id of the user. Try to send authorization user info through the header. Hope you find this helpful.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum