-1

This Question is an additinal question atached to axios resoponse work when not saving response in state and when setting state fails.

I didnt get a true answer to my question and figured I should give some examples.

I don't understand why when I'm printing my response I see the result but when I try to save it in a state I'm getting an empty array (in the response itself which mean my new state will be an empty array to...)

I've researched through the internet and all I found was examples where people didn't use promise as they should and because of that couldn't save the response but could print it.

my code

useEffect(()=>{
       props.getAllOpen.then(res=>{
       let check = res.data.data;
       console.log(check); or [console.log(res.data.data)]
       });
},[]);

Result in console

Array(2)

0: {Stations: Array(2), _id: "60c5be4be3f2262294dff893", Type: "d"}

1: {Stations: Array(2), _id: "60c5be4be3f2262294dff892", Type: "d"}

My problem

const [Data,setData] = useState([]);
useEffect(()=>{
       props.getAllOpen.then(res=>{
       setData(res.data.data);
       console.log(res.data.data);
       });
},[]);

Result in console

[]

What Am I doing wrong? any help will be appreciated.

Thank You for taking the time to help me :)

--->Full Component<---

import {React,useEffect,useState} from 'react';
let dateFormat = require('dateformat');
const NotificationTable = (props)=>{
const [Data,setData] = useState([]);
    useEffect(()=>{
       props.getAllOpen.then(res=>{
        setData(res.data.data);
       });
   },[]);
        
    // get date return true if the date is the date of current day
    function isSameDay(date) {
        let today = new Date();
        if(today.getMonth()===date.getMonth() && today.getFullYear()===date.getFullYear() 
        && today.getDay()=== date.getDay())
            return true;

        return false;
    }
    return(
            <div className = "Notification-Table">
                <div className  = "Row"> <div className = "Header-Cell">end date</div><div className = "Header-Cell">start date</div> <div className = "Header-Cell">duplicate</div> <div className = "Header-Cell">סוג</div> <div className = "Header-Cell">s</div></div>
                { [...Data.filter(e=>e.Close==="1970-01-01T00:00:00.000Z").splice(0,21),...Array(22-Data.filter(e=>e.Close==="1970-01-01T00:00:00.000Z").splice(0,21).length)].map((d,index)=>{
                    if(d)
                   { 
                    return(<div key = {d._id} className  = "Row"> 
                    <div className = "Cell">{new Date(d.Close).getFullYear()===1970?"Live":isSameDay(new Date(d.Close))?dateFormat(new Date(d.Close),"HH:MM:ss"):dateFormat(new Date(d.Close),"dd-mm-yyyy")}</div>
                    <div className = "Cell">{isSameDay(new Date(d.Open))?dateFormat(new Date(d.Open),"HH:MM:ss"):dateFormat(new Date(d.Close),"dd-mm-yyyy")}</div>
                    <div className = "Cell">{d.Duplicate}</div>
                    <div className = "Cell">{d.Type}</div> 
                    <div className = "Cell">{d.Stations}</div>
                    </div>);}
                    else
                   {
                       return(<div key = {index} className  = "Row"> 
                    <div className = "Empty-Cell"></div>
                    <div className = "Empty-Cell"></div>
                    <div className = "Empty-Cell"></div>
                    <div className = "Empty-Cell"></div> 
                    <div className = "Empty-Cell"></div>
                    </div>);}
                    })}
            </div>
);
};

export default NotificationTable;

---> Axios request <---

export const getAllOpenNotification = ()=> api.get('/opennotifications');

--->Mongoose Query<---

getOpenNotification = async (req, res) => {
    await Notification.find({Close:"1970-01-01T00:00:00.000Z"}, (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: `Open Notification not found` });
        }
        return res.status(200).json({ success: true, data: notifications });
    }).catch(err => console.log(err));
};

--->Route<---*

router.get('/opennotifications',getOpenNotification);
aylon
  • 56
  • 1
  • 8

2 Answers2

1

It is difficult to give you an exact fix is without having access to your repository, but I have had this issue when not creating a deep copy.

Try the below example.

const [data,setData] = useState([]);

useEffect(()=>{
    props.getAllOpen.then(res=>{
    setData([...res.data.data]);
    console.log(res.data.data);
 });
},[]);

console.log('Data: ', data);
// Return something
return ();
Vuk
  • 693
  • 4
  • 14
  • I've tried your solution anf it gave me (2) [{…}, {…}] length: 0 when I do Data[1] I'll get what I need but if Itry to make a forEach loop or .map function it says I dont have anything in the array. – aylon Jun 13 '21 at 11:41
  • Sorry that doesn't make sense. So it adds two elements to the array? Where are you doing the map can you update to include more of the code. – Vuk Jun 13 '21 at 12:14
  • [link](https://prnt.sc/159g5az) that's what I've got in console when I tried your code – aylon Jun 13 '21 at 12:30
  • You shouldn't be looking at the log in the useEffect hook. You should log the state value of Data just before you return in your component to get a better picture of what is wrong. Console logs can be deceiving because they show you the value of the variable at execution, not at the time in the code. See my updated example. – Vuk Jun 13 '21 at 13:56
  • I'll try it when I can and update here. Thank you – aylon Jun 13 '21 at 14:52
  • I've tried to console log as you suggested and got the same result – aylon Jun 14 '21 at 05:09
  • Can you post your component in full, it is still unclear what issue you're having as you've said above that data has the correct data but you just can't map through it? – Vuk Jun 14 '21 at 05:24
0

You are doing nothing wrong, but console.log() is asynchronic function. so, when you print res.data.data, the printing may be done before assignment. so you get an empty array even though the assignment has been made.

To fix this problem, you can see here.

אנונימי
  • 304
  • 2
  • 7
  • I'm not calling Data(my state) in my example. I'm calling the res itslef. doesn't it suppose to run the console.log line only after it get response? Furthermore I've tried to make another state and useeffect that will render again when I get new Data Something like this: `useEffect(()=>{ props.getAllOpen.then(res=>{ setTempData(res.data.data); }); },[]); useEffect(()=>{ setData(TempData); },[TempData]);` – aylon Jun 13 '21 at 11:48