Using the Redux Thunk Middleware to Quickly Send API Requests in React Native

Sunny Singh
5 min readApr 23, 2020

If you’re using Redux, you’ll notice that your actions return an object and your reducers are synchronous. Actions return an object that contains the type of action being used and some data while reducers return a new state. Everything is synchronous.

But what if you wanted to send some API requests and then use that data as the payload that gets sent to your reducer? But wait, API requests are asynchronous. How can we work around this?

That’s where Redux Thunk can help you out. It’s a middleware for Redux. Before I get into implementing Redux Thunk into your project, I want to talk about some background information so you really understand what’s going on.

If you believe you understand all of the background information, you can skip over this section and go straight to the implementation.

Background Information

There are many things that go into making Redux Thunk work. In order to understand all of it, I’ll go over what a thunk is in software engineering and what middleware does.

What is a Thunk?

A thunk, in simple English, is simply a function that is returned by another function. So a thunk would look something like this:

function some_function() {
// Return a function so we can do it later...
return function thunk() {
console.log('Do something.');
}
}

If you were to call some_function(), you would get back a function that you can run at some other time. For example, you would use the above function in the following manner:

// Store the returned function
const returned_function = some_function();
// ...some other codereturned_function();

That’s essentially what a thunk is. It’s just a function that is returned from another function.

What is Middleware?

In software, middleware usually acts as the middleman between two entities. For example, an operating system can somewhat be viewed as a middleware as it communicates with both the hardware and the software.

In terms of Redux, middleware is some code that runs in between your actions and your reducers. So imagine that you call some action function. Normally, without some middleware, the object would immediately be passed to the reducer file. However, with some middleware, there’s some code that runs in between the action and the reducer. The middleware acts as the middleman between the actions and the reducers.

Putting it Together

What Redux Thunk essentially does is that it checks if any function is passed back from the action and then executes that function before passing on something to the reducer. Matter of fact, the entire Redux Thunk library is very small. Here it is:

function createThunkMiddleware(extraArgument) { 
return ({ dispatch, getState }) => next => action => {
// This gets called for every action you dispatch.
// If it’s a function, call it.
if (typeof action === ‘function’) {
return action(dispatch, getState, extraArgument);
}
// Otherwise, just continue processing this action as usual
// Basically, pass it on to the reducer
return next(action);
};
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;

Something to note is that Redux will pass two parameters to any function that you return. The two parameters are dispatch and getState. The dispatch parameter allows you to invoke new actions if you need to and the getState parameter allows you to access the current state.

This is useful since if you want to run some asynchronous code with Redux, you can use the dispatch parameter to send data to your reducer file once the asynchronous code is done running.

Now let’s get into the implementation of Redux Thunk.

Implementation of Redux Thunk

First, make sure that you have Redux Thunk installed for your project. If you don’t, depending on if you are using Expo or not, you can run the following command:

If you are using Expo:
expo install redux-thunk

If you’re using regular React Native CLI:
npm -i --save redux-thunk

Creating an Action Function That Returns a Function

From here, you can use Redux Thunk to return a function from your action function. In my example, I will be using Axios to call some API. Remember that a thunk is a function that is returned from some function and that Redux passes it dispatch and getState. Below is an example:

export loggedInUser = (user) => {
return {
type: 'LOGGED_IN_USER',
payload: user
};
};
export const loginUser = (username, password) => {
return (dispatch, getState) => {
const params = {
username: username,
password: password
};
axios.post(uri + '/user/login', params).then((response) => {
if (response['success'] == true) {
// Login the user using dispatch
dispatch(loggedInUser(response['user']));
} else {
// Send the error from API back
dispatch(error(response['error']));
}
});
}
}

In this example, we are defining some action function that takes in a username and a password. The function then returns another anonymous function. This anonymous function simply uses Axios to send a POST request to an API. After that, it checks if the response was successful or not. If the response was successful, it will dispatch another action to save the data. If the response was unsuccessful, it will dispatch a different action to save the error message that can be later displayed.

From here, we can use our reducer to update our state. The data we get from our Axios response is passed to our reducer.

That’s pretty much if for Redux Thunk. You create a function that returns a function. The returned function contains some asynchronous code and it runs as middleware. Once the data is returned, it calls dispatch and invokes the reducer function.

Conclusion

This post went over what Redux Thunk is and how you can use it in order to send data from an API to your Redux state management. We talked about what the meaning of thunk is and what middleware is. Finally, we implemented Redux Thunk to send a POST request to log in a user.

If you were able to derive any value, be sure to hit that ‘clap’ button to give this post some claps.

If you have any questions, feel free to reach out to me, it’s @SunnyChopper on pretty much every social media platform out there.

Hopefully, this post was helpful to you. Appreciate it.

--

--

Sunny Singh

Backend developer passionate about leveraging practical solutions. Sharing insights on using software development and AI to solve problems. Connect for more!