Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
How can I return two different strings based on try/finally blocks using setTimeout

I am trying to return two different states based on the timer set on setTimeout in try/finally blocks but once I return the state in the try block, the finally block does not return anything. Is there a way to get around this? I am trying to pass a string value that will be a notification then 5 seconds later return an empty string so the notification can clear...

import { createSlice } from "@reduxjs/toolkit";

const notificationSlice = createSlice({
  name: 'notification',
  initialState: '',
  reducers: {
    createNotification: {
      reducer(state, action) {
        try {
          state = `You voted for ${action.payload[0]}`
        } finally {
          setTimeout(() => {
            state = ' '
          }, 5000);
        }
        return state
      },
      prepare(...args) {
        return {
          payload: args
        }
      }
    }
}})

export const { createNotification } = notificationSlice.actions
export default notificationSlice.reducer
about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

Because setTimeout is async, the return state actually gets run before the setTimeout callback runs.
So your state gets returned first, then when the callback runs, it will do nothing. I don't think the try...finally will make any difference here.
You would have to implement another reduces method, for closing the notification, and run that with a setTimeout.
(sorry not sure how that would look here, but that's what I had to do when I worked with react reducers)

about 4 years ago · Santiago Gelvez Denunciar

0

You can return an object instead of a string.

try {
    state.foo = `You voted for ${action.payload[0]}`
} finally {
    setTimeout(() => {
        state.foo = ''
    }, 1000);
}
return state
about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda