redux saga fetch json code example

Example: redux saga fetch json

// USER ACTION CREATOR
export const userState = {};
export const RECEIVED_ALL = "RECEIVED_ALL";
export const REQUEST_ALL = "REQUEST_ALL";

export const userRequestAllActionCreator = (type) => ({
  type: type
});


// USER REDUCER
import { userState, RECEIVED_ALL } from "../actions/user";

export const userReducer = (state = userState, action) => {
  switch (action.type) {
    case RECEIVED_ALL:
      return action.payload;
    default:
      return state;
  }
};

// USER SAGA
import axios from "axios";
import { put, takeLatest } from "redux-saga/effects";
import { REQUEST_ALL, RECEIVED_ALL } from "../actions/user";

function* userReceiveAll() {
  const { data } = yield axios.get("https://jsonplaceholder.typicode.com/users");
  yield put({ type: RECEIVED_ALL, payload: data });
}

export function* userSagaAll() {
  yield takeLatest(REQUEST_ALL, userReceiveAll);
}

Tags:

Misc Example