Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!