0

I'm trying to fetch data from my data base using mongoose and axios. I used the same code concept in some occasions. In some my axios request responded well and I've got my result.

In some, when I try to send the request I get nothing in return even though my table is not empty. After research I've found the reason behind me getting an empty array as result. When sending the axios request I get my wanted result... But when trying to save it as a state for some reason the response change to not found.

For reference here is the code I'm using in both cases:

Mongoose query

getNotifications = async (req, res) => {
    await Notification.find({}, (err, notifications) => {
        if (err) {
            return res.status(400).json({ success: false, error: err });
        }
        if (!notifications.length) {
            return res
                .status(200)
                .json({ success: true,data:[],error: `Notification not found` });
        }
        return res.status(200).json({ success: true, data: notifications });
    }).catch(err => console.log(err));
};

Axios request

export const getAllNotification = ()=>api.get(`/notifications`);

React

const[notifications_card,setNotifications_card] = useState([]);
useEffect(()=>{
getAllOpenNotification().then(res=>{
      res.data?setNotifications_card(res.data.data?res.data.data:[]):console.log()
      console.log(res); //if the line above weren't there It'll log the data, if kept as it is it 
      //will act as notifiction.length is 0 and return an epmty array
    });
},[]);

I'm using this exact same code in multiply componnent which some work perfectly fine and others react as mention above.

aylon
  • 56
  • 1
  • 8
  • can you log res.data.data and what is getting in it ?. if it's empty then update setNotifications_card(res.data?res.data:[]):console.log() – ajay 24 Jun 10 '21 at 06:45
  • I've logged it and got the data I wanted. when i didnt try to update the state. when updating the state when I console res.data.data i get empty array as nothing was found in the query... if I understand it correctly. I even tried to update it occasionly still didn't help. For some reason it does work in some places and in other not – aylon Jun 10 '21 at 06:58
  • @aylon, make sure that notifications `(data: notifications)`, is an array, because `notifications_card` expects an array. – Ani Jun 10 '21 at 07:30
  • @Ani data: data: [] success: true that's what my res object get.. i was sure it was caused by reusing the axios request and getting from the query notification.length === 0 but when I double checked it now i see I don't get error pointing that notifications not found... which is wierder. For some reason the query works returning my notifications and then after useing my set state function it clears the res.data.data... How is it possible ? – aylon Jun 10 '21 at 07:41
  • try to remove the ternary expression you are using. Instead of this `res.data?setNotifications_card(res.data.data?res.data.data:[]):console.log()` use this: `setNotifications_card(res?.data?.data)` or this `setNotifications_card(res?.data.data)`and let me know pls. – Ani Jun 10 '21 at 07:51
  • I've tried to remove every thing and do it clean. ```i've tried to do setNotifications_card(res.data.data)``` still didn't work. I think the problem isn't in what I set in my state, maybe rather something else. My response from my axios request is returning an empty array wich means my res didn't return 404. Furthermore I've tried to console log my items in my mongoose query (while not removing the setstate) and i got my elements.... – aylon Jun 10 '21 at 08:07

1 Answers1

0

I suggest you to use useState() and useEffect() Hook. Reference: https://reactjs.org/docs/hooks-intro.html I have written again axios request. If the request is successful, save the response data to response constant, otherwise set an error message.

import React, { useState, useEffect} from "react";
        import axios from "axios";

    const[notifications_card,setNotifications_card]=useState([]);
    const [message, setMessage] = useState("");
        
  useEffect(() => {
         axios
              .get("Your complete url")
              .then((res) => {
                  setNotifications_card(res?.data)
                return res.data;
              })
              .catch((error) => {
                setMessage(
                  "Sth wrong happened"
                );
        console.log("Sth wrong happened");
              });
   }, []);
Ani
  • 788
  • 3
  • 7
  • 21
  • is'nt it exactly what I did? I've used setState in my code. furthermore I dont think it will fix my problem. Maybe I'm missing something dipper ? – aylon Jun 10 '21 at 07:01
  • Oh, I just realized I didnt write in my question my useeffect and usestate code, I'll edit it, thanks – aylon Jun 10 '21 at 07:04