by Sai gowtham

How to Fetch Data in React Redux using Hooks

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 to write asynchronous logic in our code like http requests.

Open your terminal and run below 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 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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course