redux fetch json code example

Example 1: redux fetch data using axios

// action type
const FETCH_ALL = "FETCH_ALL";
const FETCH_FAIL = "FETCH_FAIL";

// initial state
const fetchState = {
  users: [],
  error: ""
};

//action creator
const fetchDataAsync = () => {
  return (dispatch) => {
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then(({ data }) => dispatch({ type: FETCH_ALL, users: data }))
      .catch((err) => dispatch({ type: FETCH_FAIL, error: err }));
  };
};

// reducer
const fetchReducer = (state = fetchState, action) => {
  switch (action.type) {
    case FETCH_ALL:
      return action.users;
    case FETCH_FAIL:
      return { ...state, error: action.error };
    default:
      return state.users;
  }
};

// store
const reducers = combineReducers({ users: fetchReducer });
const store = createStore(reducers, applyMiddleware(logger, thunk));

//fetchAllData component
import React, { useEffect } from "react";
import { connect, useDispatch } from "react-redux";
import { fetchDataAsync } from "../redux/Action";

const FetchData = (props) => {
  
  const dispatch = useDispatch();
  
  useEffect(() => {
    dispatch(fetchDataAsync());
  }, []);

  return (
    <>
      <ul>
        {props.users.map((user) => (
          <li key={user.id}>
            {user.name} | {user.email}
          </li>
        ))}
      </ul>
    </>
  );
};

const mapStateToProps = (state) => {
  return { ...state };
};

export default connect(mapStateToProps)(FetchData);

Example 2: 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);
}