react reducer axios code example

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