Start making API calls using React redux-thunk

Start making API calls using React redux-thunk

ยท

6 min read

Introduction

Redux and React js an awesome pair to have, But a pain to work with if you're a beginner. Hopefully, this article will help in making it easy for you.

But first what is Redux.

Redux

Redux is a state management tool that helps you in managing the states. What do I mean by managing the state. Think of a scenario that you built a web app that allows users to login, Now after they have logged in you have to display there information on a lot of components.

The first option that would come to your mind if you're starting out is that you should pass it through props. But believe me when I say that this isn't the best option and will make things more complicated than it should be.

The second option you have is to use some state manager like Redux, Mobx, or context API. But we will be focusing on using Redux as this is the most popular and I'm most familiar with it.

Setting up a React project.

Now if you are trying to learn Redux you should be familiar with this, But let's go through it once more. First you have to run.

npx create-react-app your-app-name

create-react-app.png

as you can see I named my project redux-starter you can name it whatever you want.

Now once it has finished installing lets open the folder in VS Code.

open vs code.png

you should see something similar to this.

Now let's install the required packages to setup redux with react js. Run the following command in the vscode terminal. You can open your terminal using ctrl + ` or

cmd + ` if you're on a mac.

npm i react-redux redux redux-logger redux-thunk

npm i redux.png

After installing these packages run

npm start

This will start the project.

Congratulations on starting your React project. Now a chrome tab should open up and you should see something similar to this.

project started.png

Importing the required packages

Now that you have a running react project. Goto index.js and import the following at the top of the file.

// import Redux
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducer from "./redux/reducers/reducer";
import logger from "redux-logger";

const store = createStore(reducer, applyMiddleware(thunk, logger));

Ok now to go through what each one is used for.

  • react-redux is the package that connects redux with react.
  • redux is the state management tool.
  • redux-logger is just a middleware that helps you by logging into the console if there is any change in any of states.
  • redux-thunk Thunk middleware for Redux. It allows writing functions with logic inside that can interact with a Redux store's dispatch and getState methods.

Now that all of that is out of the way. Wrap your tags inside the provider tag like this and pass it the store variable.

ReactDOM.render(
  <React.StrictMode>
    // add this
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

Now I know that some of you saved and tried to check the react app, And might be facing some errors. Don't worry this should happen as we don't have the reducer file yet so let's create that.

The redux folder

In the src directory create a new folder and name it redux and create two sub-folders inside the redux folder named action and reducers. It should look something like this.

dir.png

Now that we have the files first open the index.js in the action folder and export action like this

export * from "./action";

Now in your action.js file add the following code.

export const firstAction = (data) => async (dispatch) => {
  var requestOptions = {
    method: "GET",
    redirect: "follow",
  };

  fetch("https://randomuser.me/api/", requestOptions)
    .then((response) => response.json())
    .then((result) => {
      dispatch({
        type: "firstAction",
        data: result.results[0],
      });
    })
    .catch((error) => console.log("error", error));
};

this is a dummy fetch request so that we can actually see if we are able to fetch data from the randomuser.me API. This is a simple fetch request you can also use axios if you like, But I'm using simple fetch to keep things simple.

ok the action part is done. Now let's add the following in the reducer.js file

const initialState = {
  firstState: [],
};

const changeState = (state = initialState, { type, ...rest }) => {
  switch (type) {
    case "set":
      return { ...state, ...rest };
    case "firstAction":
      return { ...state, firstState: rest.data };

    default:
      return state;
  }
};

export default changeState;

So, the variable initial state is the value of the state that it will be in beginning. The change state function is the actual stuff the type and rest are the parameters that are being passed from the action.js file. Hope that it's clear.

Updating App.js

Finally we are at the end.

It's the final countdown

In your App.js import the following

import { firstAction } from "./redux/action";
import { useDispatch, useSelector } from "react-redux";

firstAction is the action that we created in the redux/action/action.js directory, useDispatch is the hook that helps us in dispatching functions and useSelector is the hook that helps us to access our states.

in your App(props) function add a useEffect()

  useEffect(async () => {
    await dispatch(firstAction());
  }, []);

We are calling action that we created every time the component mounts.

Don't forget to import useEffect at the top

import React, { useEffect } from "react";

Ok, Finally let's call the useDispatch() and useState() at the top before the return and after initiating the function.

 const state = useSelector((state) => state);
  const dispatch = useDispatch();

Now just update your return and call the reducer state.

    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>test {state.firstState.gender}</p>
      </header>
    </div>

Once you are done your App.js should look like this.

import React, { useEffect } from "react";

import logo from "./logo.svg";
import "./App.css";

import { firstAction } from "./redux/action";
import { useDispatch, useSelector } from "react-redux";

function App() {
  const state = useSelector((state) => state);
  const dispatch = useDispatch();
  // To fetch data when component mounts.
  useEffect(async () => {
    await dispatch(firstAction());
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>test {state.firstState.gender}</p>
      </header>
    </div>
  );
}

export default App;

Now if you save and run the project you should see male or female. According to what the API returned. Like this.

Screenshot 2022-01-12 at 11.33.33 PM.png

Hopefully, you were able to get it running as well, But if in any case, you faced any issues you can ask me in the comment section I'll try my best to answer your questions, or if you want to the git repo you can find it here a follow and a star would be appreciated ๐Ÿ˜ƒ

Bye for now.

Rayan Abid Github

Rayan Abid Youtube

ย