Redux async actions in React Native with redux-thunk

Shubham Suresh Lad
Quoality
6 min readMar 15, 2021

--

As we know React Native is a JavaScript framework for writing real, natively rendering mobile applications for iOS and Android. The single codebase and will work on both devices. State management is an important part of application development and for state management the best library out there is Redux. You may think why one should use redux,

let me explain

when your app gets large and complex simple data management as parent-child (that React provides) becomes difficult using props. Multiple components are trying to communicate with multiple other components, in such cases, Redux comes in handy.

But wait we have again one more problem with a plain basic Redux store, you can only do simple synchronous updates by dispatching an action. What if you want to run any asynchronous function like API calls, here comes Redux-thunk to rescue.

Redux thunk is a middleware for redux which teaches Redux to recognize special kinds of actions that are in fact functions. When an action creator returns a function, that function will get executed by the Redux Thunk middleware. This function does not need to be pure which means it is therefore allowed to have side effects, including performing asynchronous API calls and the function can also dispatch actions.

In simple terms, Redux Thunk is the middleware that lets you call the action creators that return a function instead of the action object. That function then gets the store’s dispatch method, which is then utilized to dispatch the regular synchronous actions inside a body of the function after the asynchronous operations have been performed.

Async data flow in Redux

With the above diagram, you can see how this all together will go to work.

Ok enough talking let’s get into code

Steps to implementing redux and redux-thunk

  1. Create a Simple App
  2. Install necessary package to implement redux
  3. Create a reducer
  4. Create actions
  5. Create redux store
  6. Pass the store to the app
  7. Accessing global state
  8. Dispatch actions
  9. Running the app
  10. Conclusion

Create Simple App

react-native init reduxThunkApp

This will create a basic React-native app that you can run on a device or simulator. (either Android or iOS)

Install necessary package to implement redux

yarn add redux react-redux redux-thunk

React-Redux is the official React binding for Redux. It lets your React components read data from a Redux store, and dispatch actions to the store to update data.

here are the files that we are creating in this post

files we are going to create

Create a reducer

Before this, we have to create constants file constants.js

The receiver of the action is known as a reducer. Whenever an action is triggered, the state of the application changes. The handling of the application’s state is done by the reducers.

A reducer is a pure function that computes the next state based on the initial or previous state. It returns the same output if the state is unchanged. It takes two inputs — the state and action—and must return the default state.

UserReducer is the main action handler of our store and updates the state of the store according to the action dispatched in the application.

Create actions

Before creating action we need to create a separate file for our API calls, I like to put all API calls in a single folder.

Actions are payloads of information that send data from your application to your store. They are the only source of information for the store.” this means if any state change necessary the change required will be dispatched through the actions.

They can be triggered in the button press, timers, or network requests.

As you can see fetchUserAction function receives the user name from the component where it was dispatched and the next function receives the dispatch method this is because of the redux-thunk middleware.

also, you can see we are returning a promise this is because in some phase of development there will be a need to perform some actions based on the response from the API like showing toast or firing alert this code will help you to achieve that.

Create redux store

A store is an object that brings and actions and reducers together. It provides and holds the state at the application level instead of individual components. Redux is not an outspoken library in terms of which framework or library should use it.

The combineReducer function combines all the different reducers into one and forms the global state. So this is the global state of our whole application.

Pass the store to the app

To bind this Redux store in the React Native app, open the entry point file Index.js and import the store as well as the high order component (HOC) Provider from the react-redux package. This Provider makes the Redux store available to the rest of your app using connect() method or useSelector() hook.

Accessing global state

hmm hmm Did I provide you our App.js file, No then let's head back to our App.js file

Probably I will share the App.js file at the end of this article as the main concern here is that how we can access the redux state in our functional component and also how we can dispatch the actions.

In many articles, you will find the connect() method but it’s outdated now we will use a new hook method to access the Redux store

React Redux now offers a set of hook APIs as an alternative to the existing connect() Higher Order Component. These APIs allow you to subscribe to the Redux store and dispatch actions, without having to wrap your components in connect().

To access state when managing it with Redux, the useSelector hook is provided. It’s similar to the mapStateToProps the argument that’s passed inside connect(). It allows you to extract data from the Redux store state using a selector function.

Open the App.js file and import this Hook from react-redux:

now we have access to the usersData fetched from GitHub but before that let’s write a search bar where we will input a username and on search, it will dispatch our fetchUserAction Action.

Dispatch actions

For this we will be using the useDispatch hook, This hook returns a reference to the dispatch function from the Redux store. You may use it to dispatch actions as needed.

first, we imported useDispatch from the react-redux and then we need to define dispatch after useSelector in our functional component

Next, dispatch the actions called fetchUserAction to trigger this event

The advantage useDispatch hook provides is that it replaces mapDispatchToProps and there is no need to write boilerplate code to bind action creators with this hook now.

Now let's head back to App.js and create a card for user Profile

Running the app

Now let’s run the application. From the terminal first, start the JS server and then run the android app from another terminal window

npx react-native start
npx react-native run-android

For your reference here is the complete snippet of App.js

Conclusion

This is how we call asynchronous operations using redux-thunk. And with the addition to hooks such as useSelector and useDispatch, we not only reduce the need to write plentiful boilerplate code but also provide the advantage of using functional components.

You can find the complete code for this tutorial in the GitHub repo.

--

--