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.