1

This is an example code from the easy peasy docs but the same question goes for createThunk from redux-toolkit:

function MyComponent() {
  const saveTodo = useStoreActions(actions => actions.todos.saveTodo);
  const onSaveClick = useCallback(
    // We chain on the promise returned by dispatching the thunk
    //                                  
    () => saveTodo('Learn easy peasy').then(() => {
      // redirect on success
      history.push('/done');
    }),
    [saveTodo]
  );
}
  1. Lets say saveTodo saves a todo in store(changing the store). changing the store triggers a re-render of subscribed components. So, how does the "then" logic execute anyway?
  2. Lets say that saving the todo will not re-render the component immediately but after executing the logic in "then". What if I want to display a loading spinner while saving the todo and just then execute the "history.push..."?
morh
  • 101
  • 1
  • 9

1 Answers1

1

The sequence would be:

  1. Component calls saveTodo()
  2. The saveTodo function I assume is one that already wraps the actual call to dispatch, so internally that runs dispatch(actualSaveTodoThunkActionCreator()). This creates a new "thunk function" and passes it to dispatch.
  3. The thunk middleware sees that the "action" is actually a thunk function, stops it from continuing onwards, and calls it: https://redux.js.org/usage/writing-logic-thunks#how-does-the-middleware-work
  4. The body of the thunk runs, and returns a Promise
  5. The thunk middleware returns that Promise.
  6. The returned Promise is passed back through any other middleware, and finally returned from the original dispatch() call
  7. The code in useCallback() gets the Promise, and chains a .then() call on it
  8. Normal Promise resolution happens at some point in the future.
  9. The Promise internally invokes the .then() callback after it has been resolved.

Per the second question, you could set loading state in the component before and after the dispatch:

https://redux.js.org/tutorials/essentials/part-5-async-logic#checking-thunk-results-in-components

markerikson
  • 63,178
  • 10
  • 141
  • 157
  • Thank you but you missed my point. When the component rerenders(after updating the store) the previous onSaveClick is destroyed but a promise is returned to it. can you understand the conflict? – morh Aug 21 '21 at 21:16
  • Ah... sorry, no, I'm afraid I'm really not sure what you're asking here, then. Can you clarify? – markerikson Aug 22 '21 at 16:03
  • Within all the steps you mentioned where the component re-rendering takes place? before the promise gets resolved or after or in between ? thanks. – morh Aug 23 '21 at 15:55
  • Mmm... depends on where in that sequence you're dispatching the action after the request is done. – markerikson Aug 23 '21 at 16:01