Student: Fang, I failed the interview again today.

Fang: Why? Didn’t answer?

Student: The interviewer asked Redux first, and I answered the question as you asked. But, he added, do you know redux-thunk? What does it do

Fang: What do you say?

Student: I said, yeah, it can use redux middleware to make Redux support asynchronous action

Fang: That’s right

Student: And then he said, can you write the source code for Redux-Thunk by hand?

Fang: Can’t you write?

Student: I haven’t seen it…

Fang: Do you need to see this? After you know how Redux works, it takes seconds to write thunk

Student: Huh? That simple?

Fang: Don’t believe me, LET me show you the source code of redux-thunk:

There are 14 lines, and I can simplify them with you to seven more:

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

  return next(action);
};
export default thunk
Copy the code

Describe the logic of this code in Chinese:

  1. If action is a function, call that function
  2. If the action is not a function, it is passed to the next middleware

One more simplification: Call an action when you find it is a function.

Student: That’s all it takes for Redux to support asynchronous action

If there is no redux-thunk asynchronous action, you can create an action that requests data and then creates an action that updates data.

Another option is to send a request directly and create an “update data” action after receiving the data.

Student: What about redux-Thunk?

With redux-thun, action can be a function:

const action = function(dispatch) {
  return fetchUsers().then(
    (users) => dispatch({type:'updateUsers', payload: users}),
    (error) => dispatch({type:'updateUsersError'}),
  );
};
dispatch(action)
Copy the code

So this action is going to get called, and then at some point in the future you’re going to create an updateUsers action, so we can call it an asynchronous action.

Student: It feels like I’m pulling my pants off and farting. Is it any different than if I call this function myself?

Redux-thunk: No difference, redux-thunk is calling this function for you.

Student: The interviewer asked for that code

Fang: Actually, he probably wants to see if you have a good understanding of the redux-related ecology. Maybe he is waiting for you to answer this question and ask if you can write Redux-saga by hand

Student: Good boy, what is that

Fong: Talk to you next time, this time let you understand redux-thunk.

Student: I do understand, thank you.

To the end.