Для асинхронных запросов следует использовать
redux middleware, например
redux-thunk:
import { fetchInitialDataApi } from './api';
const FETCH_DATA_REQUEST = 'FETCH_DATA_REQUEST';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_ERROR = 'FETCH_DATA_ERROR';
const fetchDataRequest = () => ({ type: FETCH_DATA_REQUEST });
const fetchDataSuccess = data => ({
type: FETCH_DATA_SUCCES,
payload: data,
});
const fetchDataError = error => ({
type: FETCH_DATA_ERROR,
payload: error,
});
const fetchData => async dispatch => {
try {
dispatch(fetchDataRequest());
const { data } = await fetchDataApi();
dispatch(fetchDataSuccess(data));
} catch error {
dispatch(fetchDataError(error));
}
};
const initialState = {
data: {},
isLoading: false,
isError: false,
error: null,
};
export default function(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case FETCH_DATA_REQUEST:
return {
...state,
isLoading: true,
isError: false,
error: null,
};
case FETCH__DATA_SUCCESS:
return {
...state,
data: payload,
isLoading: false,
};
case FETCH_DATA_ERROR:
return {
...state,
isLoading: false,
isError: true,
error: payload,
};
default:
return state;
}
}