Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
How to disable an active item after dispatch?

I would like to create notifications that expire after a set amount of seconds.

I have created a property which is 'active' and when toggled to false it will hide.

Ideally, it would be nice to have the expiry automatically set in the slice, i.e. run the disable reducer within the runtime of the notify reducer but i'm not sure this is good practice, and am not sure how to pull it off.

What is the best way to pull this off? I was thinking of adding an expiry date on each item but since the 'active' field is already there I would like to set a timeout and toggle it to false after 3 seconds..

Notification component:

export function Notification() {
    const dispatch = useDispatch();

    function disableAlert(id: number) {
        dispatch(disable({'id' : id}));
    }

    const notification_list = useSelector(getNotification);
    if (notification_list && notification_list.length > 0) {
        return notification_list.map((notification: any, index: number) =>
                notification.active ?
                    <Alert onClose={() => disableAlert(index)} style={{bottom: 50 * index}} severity={notification.mode}>{notification.message}</Alert> :
                    console.log(notification)
        )
    }

    return <></>
}

Currently I have these slices:

const disableMessage = (state: any, message_id: number) => {
    return state.messages.map((message:any) => message.id === message_id ?
        {...message, active: !message.active} :
        message
    );
}

export const notificationSlice = createSlice({
    name: 'notification',
    initialState: initialState,
    reducers: {
        notify: (state, action) => {
            const { message, mode, active } = action.payload;
            state.messages.push({id: state.messages.length , message : message, mode: mode, active: active});
        },
        disable: (state, action) => {
            const { id } = action.payload;
            state.messages = disableMessage(state, id);
        }
    }
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It is convention that reducers never contain any type of logic. I recommend to stick with this.

This leaves either the action or the Notification component. For me it makes more sense to tie the disable to the rendering of the individual notification so I would start the timeout there.

Ideally, you can split your <Alert/> component into the presentation and logic. Something similar to:

const NotificationAlert = ({ disableAlert, id }) => {
  const notification = useSelector((state) => selectNotificationById(state, id));

  const handleClick = useCallback(() => {
    disableAlert(id);
  }, [disableAlert, id]);

  useEffect(() => {
    setTimeout(() => disableAlert(id), 3000);
  }, [disableAlert]);

  return (
    <Alert
      onClose={handleClick}
      style={{bottom: 50 * id}}
      severity={notification.mode}>{notification.message}</Alert> 
};

And

export function Notification() {
    const dispatch = useDispatch();

    // memoize handler with useCallback
    const disableAlert = useCallback((id: number) => {
        dispatch(disable({'id' : id}));
    }, [dispatch]);

    // Filter for active notifications already in your selector
    const notificationIds = useSelector(getActiveNotificationIds);

    return notificationIds.map((id) =>
        <NotificationAlert disableAlert={disableAlert} id={id} />
    );
}

Also, make sure your disableAlert action is setting active to false rather than toggling it!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda