question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

useNotificationCenter and localStorage

See original GitHub issue

Good afternoon. In my react application I use useNotificationCenter. I need to make sure that messages and the number of unread messages are stored in localStorage. It is necessary that after reloading the page, you can view messages - read or unread, see the number of messages. And so that after reloading the page, I could again correctly delete messages and make them read. Here is an example code :

import React, { useEffect } from "react";
import { useNotificationCenter } from "react-toastify/addons/use-notification-center";
import { toast, ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

const Dash = () => {
  const { clear, markAllAsRead, markAsRead } = useNotificationCenter();
  const { notifications } = useNotificationCenter({
    data: JSON.parse(localStorage.getItem("notifications")),
  });
  const { unreadCount } = useNotificationCenter(
    JSON.parse(localStorage.getItem("unreadCount"))
  );
  const showToast = () => {
    toast("Hello World", {
      data: {
        title: "Hello World Again",
        text: "We are here again with another article",
      },
    });
  };

  const showErrorToast = () => {
    toast.error("Hello World", {
      data: {
        title: "Error toast",
        text: "This is an error message",
      },
    });
  };

  useEffect(() => {
    if (notifications.length !== 0) {
      localStorage.setItem("notifications", JSON.stringify(notifications));
    }
  }, [notifications]);

  useEffect(() => {
    if (unreadCount !== 0) {
      localStorage.setItem("unreadCount", JSON.stringify(unreadCount));
    }
  }, [unreadCount]);

  return (
    <div>
      <p>{notifications.length}</p>
      <button onClick={showToast}>Default</button>
      <button onClick={showErrorToast}>Error</button>
      <br />
      <br />
      <button onClick={clear}>Clear Notifications</button>
      <button onClick={() => markAllAsRead()}>Mark all as read</button>
      <ul>
        {notifications.map((notification: any) => (
          <li
            onClick={() => markAsRead(notification.id)}
            key={notification.id}
            style={
              notification.read
                ? { background: "green", color: "silver", padding: "0 20px" }
                : {
                    border: "1px solid black",
                    background: "navy",
                    color: "#fff",
                    marginBottom: 20,
                    cursor: "pointer",
                    padding: "0 20px",
                  }
            }
          >
            <span>id: {notification.id}</span>
            <p>title: {notification.data.title}</p>
            <p>text: {notification.data.text}</p>
            <p>unreadCount: {unreadCount}</p>
          </li>
        ))}
      </ul>
      <ToastContainer />
    </div>
  );
};
export default Dash;

As a result, the ‘notifications’ messages and the number of ‘unreadCount’ messages end up in localStorage. After updating the page, they are there. But firstly, the value of the unread Count is displayed incorrectly, and secondly, the delete message buttons and the “make read” button do not work with all old messages. Please tell me how to make the code work correctly with localStorage.

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:13 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
85arcommented, Aug 24, 2022

Awesome Everything works. Just need it like this: localStorage.removeItem("notifications") Thank you.

0reactions
85arcommented, Aug 25, 2022

There is such a task. A certain function triggers the creation of data on the backend. The result is recorded as a response when a get request is sent to the endpoint. After starting the function, I need to knock on the endpoint, and depending on the status, output first: the process is started, the process is successfully completed or an error.

const myFunction = () => {
  ...
  myPromise(id);
}

async function myPromise(myId: number) {
  const toastId = toast.loading("Loading data");
  const response = await myService.getStatus({
    params: {
      id: myId,
    },
  });
  if(response.status === 'running') {
    toast.update(toastId, {
      render: () => 'In progress',
      type: 'info'
    })
  }
  if(response.status === 'success') {
    toast.update(toastId, {
      render: () => 'Done',
      type: 'success'
    })
  }
}

I don’t understand how in this case I can send a get request to the endpoint several times, change the toast status in the process and stop the request after the status becomes success. But in this example, I only make a get request once, and that’s wrong.

Rewrote the function via setInterval, but notifications don 't hide:

const myPromise = (myId: number) => {
  const toastId = toast.loading("Loading data");
  let intervalId = setInterval(async() => {
  const response = await myService.getStatus({
    params: {
      id: myId,
    },
  });
  if(response.status === 'running') {
    toast.update(toastId, {
      render: () => 'In progress',
      type: 'info',
autoClose: 2500
    })
clearInterval(intervalId)
  }
  if(response.status === 'success') {
    toast.update(toastId, {
      render: () => 'Done',
      type: 'success',
autoClose: 2500
    })
clearInterval(intervalId)
  }  
  }, 30000)
}

I understood a little. Need isLoading: false

But my messages that the data is loaded do not show the text in the Notification Center

Read more comments on GitHub >

github_iconTop Results From Across the Web

How can I store Push Notification alert message in UserDefault?
Push Notifications in your case. However, just a thought, you can simple append the notifications to local storage or a txt file on...
Read more >
userNotificationCenter(_:didReceive:withCompletionHandler:)
The user's response to the notification. This object contains the original notification and the identifier string for the selected action.
Read more >
Local and Remote Notification (iOS) | by Abhishek Kumar
Notifications are way to inform users about updates, new features and new data available for your app. Even if your app is not...
Read more >
[expo-notifications] Background notification tasks not working
Hello,. I did totally the same, but on iOS, I have this warning : " Error: Background remote notifications have not been configured....
Read more >
Verify Push and Silent Device Approval Best Practices ... - Twilio
Learn about best practices for using Twilio's Verify API Push channel in production including security, performance, testing, and more with this overview.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found