Redux Thunk - What is it?

Redux Thunk - What is it? 


To start off, lets first understand that Redux Thunk is Middleware. What is redux middleware?
Middleware provides a bridge between the action and the reducer.

Ok, I'm guessing your next question....what's a Thunk? Well, a Thunk is actually an older term for a function. Redux Thunk, instead of returning an object, actually returns a function.

Lets go back a little and walk through what's happening.

First the user clicks a button:

<Button onClick={this.handleOnClick}>Click Me</Button>

When the user clicks the button, the handleOnClick function is called. It looks like this:


handleOnClick = () => {

     this.props.actionCreator()  //calls the action creator
}

The handleOnClick function calls the this.props.actionCreator. This is where everything starts.
The action creator's goal is to connect with the api and either add, edit or remove data from the database and then send back updated state.

Here is what an action creator looks like that uses redux thunk:


export const getMemberList = (club_id) => {

  return dispatch => {
    return fetch(`http://localhost:3001/api/clubs/${club_id}/users`) //returns the result of a get request from the database
      .then(response => response.json()) //converts the response from the fetch request to json
      .then(members => dispatch(updateMembers(members, club_id))) //takes the converted response and dispatches an action, including the updated data. 
      .catch(error => console.log("error from getMembers", error)) //if something goes wrong, it outputs the errors to the console.

    }
};

This action creator is for fetching a list of members from the database. 
It takes in a club_id and uses that as part of the url. 

By default, action creators return an action and were not made to be asynchronous and that's where our problem is. If we didn't use redux thunk, our fetch method would return data after our action dispatched, meaning our action would be empty and no data would be updated in state. By utilizing redux thunk, we can return a function, which then allows our fetch function to "talk" with the api, update the data (in the form of a promise) and return it back to the function. It can then (.then()) be sent to the action by calling dispatch(action(action_param1, action_param2). Because dispatch is being called once the fetch function returns data, the action has data to send to the reducer. 

To recap, we use redux thunk to make sure that our action is called only once fetch has returned data from the database and not before. 


Want to know more?
Check out the github repo for redux thunk here:
https://github.com/gaearon/redux-thunk





Comments

Popular Posts