Home > front end >  How to check if the array has received a new value?
How to check if the array has received a new value?

Time:11-23

I'm trying to create a custom notification counter, which shows the number of notifications that are unread. I receive the notification content from the backend as an array. My idea is to get the first value, check if the previous length is different from the current length, and add to this counter 1(or more).

  useEffect(() => {
    axios
      .get(USER_API)
      .then((response) => {
        setNotificationList(response.data.data);
      })
      .catch((error) => console.log('error from getNotifications', error));
    });

How can I make it work?

CodePudding user response:

use the callback function in set state

  setNotificationList((prev) => {
     if(prev?.length === response.data.data.length) return prev 
     return response.data.data
   } );

CodePudding user response:

As right way could be that you place a key isRead in the backend. and setThis key to true via api when user click on the notification.

and count the length of those items who has isRead false and set it to counter.

this way you will not be dependent on local state and this will work even if app is killed or uninstalled.

useEffect(() => {
axios
  .get(USER_API)
  .then((response) => {
    const data = response.data?.data;
    const unReadItems = data.filter((item)=> !item.isRead)
    setUnReadCount(unReadItems.length)
    setNotificationList(data);
  })
  .catch((error) => console.log('error from getNotifications', error));
});
  • Related