Author -  Sai gowtham

How to Fetch Data in React Redux using Hooks

In this tutorial, we are going to learn about making an http requests in redux using hooks and redux-thunk middleware.

This tutorial assumes that you already have some basic knowledge about how to use hooks in react-redux or you can check out my React Redux hooks tutorial.

CodeSandbox demo

First, we need to install a package called redux-thunk which helps us to write asynchronous logic in our code like http requests.

Open your terminal and run the following command.

npm i redux-thunk

Now we need to enable the thunk by importing from the redux-thunk package.

index.js
import React from "react";
import ReactDOM from "react-dom";
import { createStore, applyMiddleware } from "redux";import thunk from "redux-thunk";import { Provider } from "react-redux";
import reducer from "./store";
import App from "./app";

const store = createStore(reducer, applyMiddleware(thunk));
const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
);

In the above code, we passed thunk as an argument to applyMiddleware() method with this code thunk is enabled.

Fetching data

We are using axios http client library to make the http requests.

This is our reducer function with FETCH_DATA action type.

store.js
function reducer(state = { data: "" }, action) {
  switch (action.type) {
    case "FETCH_DATA":
      return {
        ...state,
        data: action.data
      };
    default:
      return state;
  }
}

export default reducer;

Now in our App.js file, we are making an http request by clicking a fetch data button, whenever we get a response from our request we are dispatching the action type FETCH_DATA with a payload.

App.js
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";

function App() {
  const content = useSelector(state => state); //this hook gives us redux store state
  const dispatch = useDispatch(); //this hook gives us dispatch method

//async action
  function getData() {
    return dispatch => {
      axios.get("https://jsonplaceholder.typicode.com/todos/1")      .then(res =>        dispatch({          type: "FETCH_DATA",          data: res.data        })      );
    };
  }

  function onFetchdata() {
      //invoking action
    dispatch(getData());
  }

  return (
    <div className="App">
      {content.data && (
        <ul>
          <li>{content.data.id}</li>
          <li>{content.data.title}</li>
        </ul>
      )}
      <button onClick={onFetchdata}>fetch data</button>    </div>
  );
}

export default App;

Note: We can also dispatch actions whenever the component mounts by using useEffect hook.

useEffect hook example

In this example, we are dispatching the action whenever the component mounts initially.

App.js
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";

function App() {
  const content = useSelector(state => state);
  const dispatch = useDispatch();

  function getData() {
    return dispatch => {
      axios.get("https://jsonplaceholder.typicode.com/todos/1")
      .then(res =>
        dispatch({
          type: "FETCH_DATA",
          data: res.data
        })
      );
    };
  }

  useEffect(() => {    dispatch(getData());  }, []);  return (
    <div className="App">
      {content.data && (
        <ul>
          <li>{content.data.id}</li>
          <li>{content.data.title}</li>
        </ul>
      )}
    </div>
  );
}

export default App;

Code sandbox demo

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY