I want to add/change a redux state when the data is received from the backend. This state controls a loading spinner. The code below is what I thought that should work.
What am I missing?
CouriersActions.js
import axios from "axios"; import { toastOnError } from "../../utils/Utils"; import { GET_COURIERS, ADD_STATE_LOADING } from "./CouriersTypes"; export const addStateLoading = (state_loading) => ({ type: ADD_STATE_LOADING, state_loading, }); export const getCouriers = () => dispatch => { var tempx = {show: true}; addStateLoading(tempx); axios .get("/api/v1/couriers/") .then(response => { dispatch({ type: GET_COURIERS, payload: response.data }); var tempx = {show: false}; addStateLoading(tempx); }) .catch(error => { toastOnError(error); }); };
Advertisement
Answer
A simple way of solving this kind issue, create custom hook for all services and where ever you need it.
export const useCouriers = () => { const dispatch = useDispatch(); const getCouriers = async () => { try { dispatch(addStateLoading({ show: true })); const response = await axios.get("/api/v1/couriers/"); dispatch({ type: GET_COURIERS, payload: response.data, // I think this should be response.data.data }); } catch (error) { toastOnError(error); } finally { dispatch(addStateLoading({ show: false })); } }; return { getCouriers }; };
Inside component
const { getCouriers } = useCouriers(); // call where you need