Home > Back-end >  How to call a useEffect when a notification in database is stored?
How to call a useEffect when a notification in database is stored?

Time:11-29

What I have done by far is when a user sends a notification to a user, it is stored in the database of the user that has received the notification. In the front end, I have created a custom notification counter, which gets the notification length from the database and displays them in the counter. It works but its not dinamaclly fine, which means if the user wants to see the counter number it has to reload the app.

  const [unReadCount, setUnreadCount] = useState();

 useEffect(() => {
   axios
      .get(USER_API   `api`)
      .then((response) => {
         const data = response.data.data;
          setUnreadCount(data);
      })
       .catch((error) => console.log(error));
 }, [unReadCount]);

return(
<>
    {/* {unReadCount !== null && unReadCount?.length > 0 && (
      <View
         style={{
          height: '40%',
          width: '40%',
          backgroundColor: '#CF1015',
          borderRadius: Platform.OS === 'ios' ? '40%' : 23,
          position: 'absolute',
          top: -2,
          justifyContent: 'center',
          alignItems: 'center',
          right: -5,
          zIndex: 100,
     }}
     >
     <Text style={{ fontWeight: 'bold', color: '#F1E3FE' }}>{unReadCount.length}</Text>
     </View>
      )} */}

</>
)

How can I call the useEffect dynamically when a notification is added to the user database?

CodePudding user response:

what you're doing there is that when the value of unReadCount changes, to fetch that number from the API. unless there's a way for the frontend to know when the database has changed, that useEffect will never get triggered.

A different approach would be to check every few seconds to see if it changed, like here:

const YourComponent = () => {
const [unReadCount, setUnReadCount] = useState(0);
getUnread = async () => {
   const result = await axios
      .get(USER_API   `api`)
      .then((response) => {
         const data = response.data.data;
      })
       .catch((error) => console.log(error));
    return result;

}

useEffect(() => {
    const id = setInterval(() => setUnReadCount(getUnread()), 15000);
    return () => clearInterval(id);

}, []);

this creates an interval that runs the request every 15 seconds and gets the new value for unread messages. Hope it helps

  • Related