V
V
Vanya Huk2018-09-27 01:45:37
React
Vanya Huk, 2018-09-27 01:45:37

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 )
}
}

getItems is an action and makes a request to the server
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);
    }

  }

accordingly, I need to wait until the response from the server returns and update the Store and then draw the component

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Afanasy Zakharov, 2018-09-27
@afanasiyz

It is possible without redux-thunk.
Just create middleware

const someMiddleware = store => next => action => {
  if(action.type === 'Нужный_вам_экшн'){
     loadData(store.dispatch);
  }
}

where loadData is an asynchronous function
const  loadData = async(dispatch) =>{
  const resultData = await fetchDataFromServer();
  dispatch(actions.saveData(resultData));
}

Inside the component, you, accordingly, call the action "You need_action", someMiddleware will catch it, call the loadData function, which will actually make a request to the server.

S
Sergey Epifanov, 2018-09-27
@kacheleff

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

R
real2210, 2018-09-27
@real2210

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 question

Ask a Question

731 491 924 answers to any question