How to make API requests with Redux Thunk in ReactJs.

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.
Search for a command to run...

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.
No comments yet. Be the first to comment.
Introduction What's up my fellow brogrammers have you ever been assigned to write documentation for a project and don't know where to start or do you like many developers just hate the thought of writing documentation then boy do I have the solution ...

Welcome, aspiring cloud enthusiasts! 🚀 Have you ever been in a situation where you want to create an account on AWS but don't know how? If you're ready to embark on your cloud computing journey with AWS, you're in the right place! Setting up your AW...

A function to upload images to AWS S3. To use this install the following packages: npm i base64-arraybuffer npm i react-native-fs npm i aws-sdk npm i react-native-image-crop-picker Please follow the setup process if not already done react-nati...

The site in the image was the first project I built. Where it started. I was one of the kids who spent most of his time in front of the computer. Chatting with friends on Yahoo messenger and MSN. I loved to play games but with that, I was always won...

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.