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

185
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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