0
votes

When we dispatch a thunk, the corresponding promise state actions are dispatched, but how can we use "then" while the component re-renders multiple times(from the promise state actions)? it doesn't make sense to me. I don't understand the order.

import { unwrapResult } from '@reduxjs/toolkit'

// in the component
const onClick = () => {
  dispatch(fetchUserById(userId))
    .then(unwrapResult)
    .then(originalPromiseResult => {})
    .catch(rejectedValueOrSerializedError => {})
}

https://redux-toolkit.js.org/api/createAsyncThunk

2

2 Answers

0
votes

This is really usage of JavaScript Promises and not very related to React, Redux or Thunk at all.

When you call .then on a Promise, execution stops and other stuff can happen. Once the underlying Promise resolves (finishes), but at the earliest point, one tick later (meaning other code can be executed in-between), the callback passed into .then is executed. The result of that is another Promise, on which you can call .then again - which you see here.

Also see the MDN Documentation on Promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

0
votes

I see your pain. this is an illness of front end development. There is some library or toolkit for every fart, then it gets convoluted and super hard to read. + this fashionable keywords async/await just make your brain explode.

thunk is very simple redux middleware it has 7 lines of code, so I could even paste it here':

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => (next) => (action) => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

the key part starts with the keyword return. This means if your action is not actually action but a function (with the thunk type signature) it returns call to that function instead of returning call next(action). This will break the chain however it does not matter as we are not dispatching the actual action but only the function (called thunk) which dispatches another action. That is all what it does. Now when we see what thunk does we can decipher this

dispatch(fetchUserById(userId))
    .then(unwrapResult)
    .then(originalPromiseResult => {})
    .catch(rejectedValueOrSerializedError => {})

fetchUserById(userId) returns returns function in the form

(dispatch, getState) => {
  // do something;
  return somePromise;
}

which is called from the redux-thunk and the result is returned. After that you are only chaining on that promise.