0

В приложение на реакте импортирую библиотеку react-toastify - хук useNotificationCenter для использования в качестве центра уведомлений. Есть задача сделать так, чтобы входящие уведомления сохранялись и отображались и после обновления страницы. Использую localStorage. Примерный код центра уведомлений:

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", String(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;

Но в таком виде, после обновления страницы, не работает:

  • не работает кнопка "Пометить как прочитанные" и "Очистить"
  • не верно отрабатывает индикатор сообщений
  • и консоль ругается на то, что не обрабатываю null, если notications пустой

Как можно поправить код? Спасибо

5
  • А вы уверены что у вас учтены типы? unreadCount !== 0 даже если unreadCount === '0'
    – HaZcker
    17 авг 2022 в 12:17
  • unreadCount - это number, если вы об этом.
    – Артур
    17 авг 2022 в 12:22
  • и console.log(typeof unreadCount) тоже покажет что это number ?
    – HaZcker
    17 авг 2022 в 12:30
  • Должен быть number, но у меня в результате JSON.stringify(unreadCount) получается строка. Вы правы, надо это поправить. Спасибо
    – Артур
    17 авг 2022 в 12:33
  • Поправил, но мой вопрос это не решило.
    – Артур
    18 авг 2022 в 4:56

1 ответ 1

0

Надо было так:

const {
    clear,
    markAllAsRead,
    markAsRead,
    unreadCount,
    notifications
  } = useNotificationCenter({
    data: JSON.parse(localStorage.getItem("notifications"))
  });

Вопрос закрыт.

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.