0

estoy realizando un componente react "Notifications", el cual muestra diferentes notificaciones las cuales estoy haciendo como mocks y tienen esta estructura:

type NotificationType = {
    sender: string;
    notificationType:
        | "pm"
        | "follow"
        | "joined"
        | "reaction"
        | "comment"
        | "left";
    timeAgo: string;
    description?: string;
    senderProfile?: string;
    actionReciever?: string;
    read: boolean;
};

Creé un array de objetos con esas propiedades y a través de un Array.map(), llamo al componente que se encarga de mostrar la notificación individual (llamemosle "Notification"), este lee la prop read y dependiendo de esta se le agrega un estilo diferente si es true o false. Al principio todo funciona bien, pero quiero tener un botón en la App principal que cambie todas las notificaciones a leídas, esto lo hago creando un nuevo array con los mismos objetos solamente que todas van a tener la propiedad read en ´true´ y con la funcion set de useState, seteo este nuevo array, de esta manera:

const [myNotifications, setMyNotifications] = useState(notifications);

function markAllAsRead() {
    const newNotificationsArray = myNotifications.map((notification) => {
        return {
            ...notification,
            read: true,
        };
    });
    setMyNotifications(newNotificationsArray);
}

La manera en que mapeo cada objeto al componente es esta:

        {myNotifications.map((notification, i) => (
            <Notification
                key={i}
                timeAgo={notification.timeAgo}
                sender={notification.sender}
                notificationType={notification.notificationType}
                senderProfile={notification.senderProfile}
                actionReciever={notification.actionReciever}
                read={notification.read}
            />
        ))}

Utilizando las herramientas de desarrollador de React puedo ver que el cambio de estado efectivamente se hizo y el hijo se actualiza, la pregunta es como puedo hacer que desde el propio componente pueda cambiar la propiedad read, para que por ejemplo al darle clic esta cambie a true y sus correspondientes estilos cambien?

Sé que podría crear un estado en el componente "Notification" que tome como valor inicial la prop read y asociar un onClick para cambiar ese estado, pero el botón de "marcar todas como leídas" no funciona, cambia el estado en el componente padre pero no en los hijos.

Es decir de esta manera:

const [isNotificationRead, setIsNotificationRead] = useState(read)

function handleCLickNotification(){
    setIsNotificationRead(!isNotificationRead)
}

EDIT:

Añado de donde viene notifications que se usa como valor por defecto del useState, es un simple array de objetos que sirve como mocks:

const notifications: NotificationType[] = [
    {
        sender: "Mark Webber",
        notificationType: "reaction",
        senderProfile: avatarMarkWeber,
        timeAgo: "1m ago",
        actionReciever: "My first tournament today!",
        read: false,
    },
    {
        sender: "Angela Gray",
        notificationType: "follow",
        senderProfile: avatarAngelaGray,
        timeAgo: "5m ago",
        read: false,
    },
    {
        sender: "Jacob Thompson",
        notificationType: "joined",
        senderProfile: avatarJacobThompson,
        timeAgo: "1 day ago",
        actionReciever: "Chess Club",
        read: false,
    },
    {
        sender: "Rizky Hasanuddin",
        notificationType: "pm",
        senderProfile: avatarRizkiHasanuddin,
        timeAgo: "5 days ago",
        description: `Hello, thanks for setting up the Chess Club. I've been a member for a few weeks now and 
        I'm already having lots of fun and improving my game.`,
        read: true,
    },
    {
        sender: "Kimberly Smith",
        notificationType: "comment",
        senderProfile: avatarKimberlySmith,
        timeAgo: "1 week ago",
        actionReciever: "picture",
        read: true,
    },
    {
        sender: "Nathan Peterson",
        notificationType: "reaction",
        senderProfile: avatarNathanPeterson,
        timeAgo: "2 weeks ago",
        actionReciever: "5 end-game strategies to increase your win-rate",
        read: true,
    },
    {
        sender: "Anna Kim",
        notificationType: "left",
        senderProfile: avatarAnnaKim,
        timeAgo: "2 weeks ago",
        actionReciever: "Chess Club",
        read: true,
    },
];

Adicionalmente añado como esta definido el componente Notification:

const Notification = ({
    sender,
    notificationType,
    timeAgo,
    description,
    senderProfile,
    actionReciever,
    read,
}: NotificationType) => {

    return (
        <div className={`notification-container ${read ? 'read': 'not-read'}`}>
            <img
                className="sender-profile"
                src={senderProfile}
                alt="sender profile pic"
            />
            <div className="notification-main--info">
                <div className="notification-text">
                    <p className={`post-description`}>
                        <span className="sender-name">{sender}</span>
                        {`${notificationMessages[notificationType]}`}{" "}
                        {notificationType == "joined" ||
                        notificationType == "left" ? (
                            <span className="group">{actionReciever}</span>
                        ) : notificationType == "reaction" ? (
                            <span className="post">{actionReciever}</span>
                        ) : (
                            actionReciever
                        )}
                    </p>
                    <span className={`not-read--icon ${read ? 'hidden' : 'visssible'}`}></span>
                </div>
                <span className="notification-timestamp">{timeAgo}</span>
            </div>
        </div>
    );
};
3
  • A ver... no termino de entender el problema, supongo que porque falta código... Pero bien, si comprendo bien, ¿myNotifications es una copia de un prop que recibes en algún momento que es notifications correcto? De ser así, todo lo que tienes que hacer es en tu componente principal (el dueño prinicpal de las notificaciones) crear la función markAllAsRead y enviar esa función como prop al componente que le corresponda cambiar ese estado. Si comprendí mal, por favor agrega el flujo de los componentes con su código. el 13 feb. 2023 a las 23:15
  • si, notifications es simplemente un array de objetos, cada uno con las propiedades que conforman una notificación, lo copié a un estado para poder cambiar las props de las mismas. La dunción markAllAsRead ya la tengo en el componente padre, si la envio como haria desde el componente hijo cambiar solamente ese objeto. Se me ocurre pasar el estado y el set que representa la lista, aunque no se que tan eficiente sea.
    – kilex
    el 15 feb. 2023 a las 2:02
  • Entiendo... entonces todo lo que tienes que hacer es agregar un parametro opcional a la funciona markAsRead, este parametro será el id de la notificación que deseas marcar como leída y si no viene lleno, pues las marcas todas como leídas. el 15 feb. 2023 a las 18:39

1 respuesta 1

1

De acuerdo a lo que te escribí en el comentario, la solución te quedaría algo así:

const {
  useState,
  useEffect
} = React;

const notifications = [
  {
    sender: "Mark Webber",
    notificationType: "reaction",
    senderProfile: "avatarMarkWeber",
    timeAgo: "1m ago",
    actionReciever: "My first tournament today!",
    read: false,
  },
  {
    sender: "Angela Gray",
    notificationType: "follow",
    senderProfile: "avatarAngelaGray",
    timeAgo: "5m ago",
    read: false,
  },
  {
    sender: "Jacob Thompson",
    notificationType: "joined",
    senderProfile: "avatarJacobThompson",
    timeAgo: "1 day ago",
    actionReciever: "Chess Club",
    read: false,
  },
  {
    sender: "Rizky Hasanuddin",
    notificationType: "pm",
    senderProfile: "avatarRizkiHasanuddin",
    timeAgo: "5 days ago",
    description: `Hello, thanks for setting up the Chess Club. I've been a member for a few weeks now and 
      I'm already having lots of fun and improving my game.`,
    read: true,
  },
  {
    sender: "Kimberly Smith",
    notificationType: "comment",
    senderProfile: "avatarKimberlySmith",
    timeAgo: "1 week ago",
    actionReciever: "picture",
    read: true,
  },
  {
    sender: "Nathan Peterson",
    notificationType: "reaction",
    senderProfile: "avatarNathanPeterson",
    timeAgo: "2 weeks ago",
    actionReciever: "5 end-game strategies to increase your win-rate",
    read: true,
  },
  {
    sender: "Anna Kim",
    notificationType: "left",
    senderProfile: "avatarAnnaKim",
    timeAgo: "2 weeks ago",
    actionReciever: "Chess Club",
    read: true,
  },
];

const ChildrenComponent = (props) => {
  const { description, status, action } = props;
  return (
    <div>
      <p>{description}</p>
      <p>{status ? "read" : "unread"}</p>
      <button onClick={action}>click</button>
    </div>
  );
};

function App() {
  const [notificationsCopy, setNotificationsCopy] = React.useState([
    ...notifications,
  ]);

  const markAsRead = (index = -1) => {
    const copia = [...notificationsCopy];
    if (index > -1) {
      copia[index].read = true;
    } else {
      copia.map((x) => (x.read = true));
    }

    setNotificationsCopy(copia);
  };

  return (
    <div>
      <button onClick={markAsRead}>Mark All As Read</button>
      {notificationsCopy.map((x, index) => (
        <ChildrenComponent
          description={x.sender}
          status={x.read}
          action={() => markAsRead(index)}
        />
      ))}
    </div>
  );
}

ReactDOM.render( < App / > , document.getElementById('root'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="root"></div>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.