Answer the question
In order to leave comments, you need to log in
What is the correct way to use async/await in react-redux?
For example, there is a component
class A {
constructor( props ){
this.props.getItems();
}
render(){
return( true )
}
}
export const getItems = () => {
return async dispatch => {
function onSuccess(success) {
dispatch({ type: UPDATE_AJAX_PARAMS, payload: success.data});
}
function onError(error) {
dispatch({ type: UPDATE_AJAX_PARAMS, error });
}
try {
const success = await axios.post( 'http://....');
return onSuccess(success);
} catch (error) {
return onError(error);
}
}
Answer the question
In order to leave comments, you need to log in
It is possible without redux-thunk.
Just create middleware
const someMiddleware = store => next => action => {
if(action.type === 'Нужный_вам_экшн'){
loadData(store.dispatch);
}
}
const loadData = async(dispatch) =>{
const resultData = await fetchDataFromServer();
dispatch(actions.saveData(resultData));
}
add a field to the store (for example, isLoading) that is responsible for the loading status. Before executing the query, set it to true, after completion - to false. In the component, check the value of this field and only render the component when isLoading is set to false
I think you should use promises.
In my projects I do something like this:
export const getItems= () => {
return async dispatch => {
await axios.get(baseUrl + '/items', {
params: {
token: someToken
}
})
.then(res => {
dispatch({type: 'GET_ITEM', data: res.data})
dispatch({ type: 'FETCH_SUCCESS' });
})
.catch(error => {
dispatch({ type: 'FETCH_FAILED', message: error });
});
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question