redux axios middleware code example
Example 1: redux fetch data using axios
const FETCH_ALL = "FETCH_ALL";
const FETCH_FAIL = "FETCH_FAIL";
const fetchState = {
users: [],
error: ""
};
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 }));
};
};
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;
}
};
const reducers = combineReducers({ users: fetchReducer });
const store = createStore(reducers, applyMiddleware(logger, thunk));
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: nuxt axios middleware
export default function ({ $axios, redirect }) {
$axios.onError(error => {
if(error.response.status === 500) {
redirect('/sorry')
}
})
}