how to fetch data using axios in redux 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 data using axios

//EXAMPLE FETCH DATA API REDUX SAGA

// USER ACTION CREATOR
export const REQUEST_API_DATA = 'REQUEST_API_DATA'
export const RECEIVE_API_DATA = 'RECEIVE_API_DATA'

export const requestApiData = () => ({ type: REQUEST_API_DATA })

// USER REDUCER
import { REQUEST_API_DATA, RECEIVE_API_DATA } from '../actions/user'

export default (state = {}, { type, payload }) => {
  switch (type) {
    case RECEIVE_API_DATA:
      return payload.users
    default:
      return state
  }
}

// USER SAGA
import axios from 'axios'
import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import { REQUEST_API_DATA, RECEIVE_API_DATA } from './actions/user'

function* userReceiveAll(action) {
  try {
    const { data } = yield call(axios.get, 'https://jsonplaceholder.typicode.com/users')
    yield put({ type: RECEIVE_API_DATA, payload: { users: data } })
  } catch (e) {
    console.log(e.message)
  }
}
export default function* userSendAll() {
  yield takeLatest(REQUEST_API_DATA, getApiData)
}

// REDUX STORE
import { createStore, applyMiddleware, combineReducer } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { all } from 'redux-saga/effects'
import logger from 'redux-logger'
import userReducer from './reducers/user'
import userSaga from './sagas/user'

function* saga() {
  yield all([userSaga()]) 
}

export const store = () => {
 const sagaMiddleware = createSagaMiddleware()
 const store = createStore(combineReducer({users: userReducer}), 
 applyMiddleware(sagaMiddleware, logger)) 
 sagaMiddleware.run(saga)
 return store;
}

// USER COMPONENT
import React from 'react'
import { connect } from 'react-redux'
import { requestApiData } from './actions'

class User extends React.Component {
  componentDidMount() {
    this.props.fetchAll()
  }
  render() {
    const { users } = this.props.state
    const results = users.length > 0 ? users : []
    return (
      <div>
        {results.map((v) => (
          <ul key={v.id}>
            <li>{v.username}</li>
          </ul>
        ))}
      </div>
    )
  }
}

const mapStateToProps = (state) => ({ state })
const mapDispatchToProps = (dispatch) => ({ fetchAll: () => dispatch(requestApiData()) })

export default connect(mapStateToProps, mapDispatchToProps)(User)