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