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
JavaScript
x
27
27
1
import axios from "axios";
2
import { toastOnError } from "../../utils/Utils";
3
import { GET_COURIERS, ADD_STATE_LOADING } from "./CouriersTypes";
4
5
export const addStateLoading = (state_loading) => ({
6
type: ADD_STATE_LOADING,
7
state_loading,
8
});
9
10
export const getCouriers = () => dispatch => {
11
var tempx = {show: true};
12
addStateLoading(tempx);
13
axios
14
.get("/api/v1/couriers/")
15
.then(response => {
16
dispatch({
17
type: GET_COURIERS,
18
payload: response.data
19
});
20
var tempx = {show: false};
21
addStateLoading(tempx);
22
})
23
.catch(error => {
24
toastOnError(error);
25
});
26
};
27
Advertisement
Answer
A simple way of solving this kind issue, create custom hook for all services and where ever you need it.
JavaScript
1
20
20
1
export const useCouriers = () => {
2
const dispatch = useDispatch();
3
const getCouriers = async () => {
4
try {
5
dispatch(addStateLoading({ show: true }));
6
const response = await axios.get("/api/v1/couriers/");
7
dispatch({
8
type: GET_COURIERS,
9
payload: response.data,
10
// I think this should be response.data.data
11
});
12
} catch (error) {
13
toastOnError(error);
14
} finally {
15
dispatch(addStateLoading({ show: false }));
16
}
17
};
18
return { getCouriers };
19
};
20
Inside component
JavaScript
1
3
1
const { getCouriers } = useCouriers();
2
// call where you need
3