how to fetch data redux

How to Fetch Data in Redux

Fetching data in Redux is a crucial concept when building web applications. In order to fetch data, the Redux state management library provides us with a few methods such as redux-thunk and redux-saga. Let's explore some of these methods in detail.

Using redux-thunk

redux-thunk is a middleware that allows us to write action creators that return a function instead of an action. This function can then dispatch multiple actions as well as perform asynchronous operations such as fetching data. Here's an example:


// actions.js
import axios from 'axios';

export const fetchData = () => {
  return (dispatch) => {
    dispatch({ type: 'FETCH_DATA_START' });
    axios.get('https://api.example.com/data')
      .then(response => {
        dispatch({ type: 'FETCH_DATA_SUCCESS', payload: response.data });
      })
      .catch(error => {
        dispatch({ type: 'FETCH_DATA_FAILURE', payload: error.message });
      });
  }
}

// reducer.js
const initialState = { data: [], loading: false, error: null };

const reducer = (state = initialState, action) => {
  switch(action.type) {
    case 'FETCH_DATA_START':
      return { ...state, loading: true };
    case 'FETCH_DATA_SUCCESS':
      return { ...state, loading: false, data: action.payload };
    case 'FETCH_DATA_FAILURE':
      return { ...state, loading: false, error: action.payload };
    default:
      return state;
  }
}

export default reducer;

In the above example, we define an action creator called fetchData that returns a function. This function takes in dispatch as an argument and dispatches multiple actions. We use the axios library to make an API call and dispatch the appropriate actions based on the response. In our reducer, we handle these actions to update the Redux state.

Using redux-saga

redux-saga is another middleware that allows us to perform asynchronous operations such as fetching data. It uses generators to manage asynchronous control flow. Here's an example:


// actions.js
export const fetchData = (payload) => ({ type: 'FETCH_DATA', payload });

// sagas.js
import { put, takeLatest } from 'redux-saga/effects';
import axios from 'axios';

function* fetchDataSaga(action) {
  try {
    const response = yield axios.get('https://api.example.com/data');
    yield put({ type: 'FETCH_DATA_SUCCESS', payload: response.data });
  } catch (error) {
    yield put({ type: 'FETCH_DATA_FAILURE', payload: error.message });
  }
}

export default function* rootSaga() {
  yield takeLatest('FETCH_DATA', fetchDataSaga);
}

// reducer.js
const initialState = { data: [], loading: false, error: null };

const reducer = (state = initialState, action) => {
  switch(action.type) {
    case 'FETCH_DATA':
      return { ...state, loading: true };
    case 'FETCH_DATA_SUCCESS':
      return { ...state, loading: false, data: action.payload };
    case 'FETCH_DATA_FAILURE':
      return { ...state, loading: false, error: action.payload };
    default:
      return state;
  }
}

export default reducer;

In the above example, we define an action creator called fetchData that dispatches a single action. In our sagas.js file, we define a saga function called fetchDataSaga that makes an API call using axios and dispatches the appropriate actions based on the response. We use the takeLatest function to ensure that only the latest dispatched action is handled by the saga. Finally, in our reducer, we handle these actions to update the Redux state.

In conclusion, fetching data in Redux is an important concept that can be achieved using various methods such as redux-thunk and redux-saga. These methods allow us to perform asynchronous operations such as API calls and update the Redux state accordingly.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe