Skip to main content

Command Palette

Search for a command to run...

How to make API requests with Redux Thunk in ReactJs.

Updated
3 min read
How to make API requests with Redux Thunk in ReactJs.
R

I am a full stack developer from Lahore, Pakistan. I'll be writing articles about latest Web technologies and frameworks.

Happy to see you here.

Making API requests in a React application can be a bit tricky, but using the Redux Thunk middleware makes it a lot simpler. In this blog post, we'll go over the basics of making API requests using Redux Thunk in a React application.

First, let's set up our project. We'll be using vite to set up our basic React structure, so just run the following (if you want to use cra you can use that as well totally up to you)

npm create vite@latest my-react-app --template react

and we'll also be using the Redux, Redux Thunk, and Axios libraries to handle our API requests.

So just install these packages using the command

npm i redux react-redux redux-thunk axios

Once our project is set up, we'll need to configure our store to use the Redux Thunk middleware. This is done by importing the applyMiddleware function from the Redux library and passing in the thunk middleware as a parameter.

import { createStore, applyMiddleware } from 'redux';

Next, we'll create an action that will handle our API request. This action will be a function that returns a function, which will be executed by the Redux Thunk middleware. The inner function will make the API request using the Axios library and dispatch a new action with the data from the API.

//create action
export const fetchData = () => {
    return (dispatch) => {
        axios.get('https://jsonplaceholder.typicode.com/users')
            .then((response) => {
                dispatch({ type: 'FETCH_DATA', payload: response.data });
            })
            .catch((error) => {
                console.log(error);
            });
    }
}

Once our action is set up, we'll need to create a reducer that will handle the data from the API. This reducer will update the state with the data from the API and trigger a re-render of our component.

Finally, we'll create a component that will make use of the data from the API. This component will use the useEffect hook to make the API request and the useSelector hook to access the data from the API.

Here is an example of how it would look like:

//configure store
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

const store = createStore(rootReducer, applyMiddleware(thunk));

//create action
export const fetchData = () => {
    return (dispatch) => {
        axios.get('https://jsonplaceholder.typicode.com/users')
            .then((response) => {
                dispatch({ type: 'FETCH_DATA', payload: response.data                 });
            })
            .catch((error) => {
                console.log(error);
            });
    }
}

//create reducer
const initialState = {
    data: []
}

export const rootReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'FETCH_DATA':
            return { ...state, data: action.payload }
        default:
            return state;
    }
}

//create component
import { useEffect, useSelector } from 'react-redux';

function MyComponent() {
    const data = useSelector((state) => state.data);

    useEffect(() => {
        store.dispatch(fetchData());
    }, []);

    return (
        <div>
            {data.map((item, index) => (
                <div key={index}>
                    <p>{item.name}</p>
                    <p>{item.email}</p>
                </div>
            ))}
        </div>
    );
}

That's it! Now you know how to make API requests using Redux Thunk in a React application. It's a powerful way to handle API requests in a clean and organized manner.

Share your thoughts if you found it useful. Please share your thoughts.

More from this blog

R

Rayan Abid's journey to becoming a better developer

15 posts

I am a full stack developer from Lahore, Pakistan. I love working on mostly Javascript related frameworks such as React and also love working with node js.