user3224271
user3224271

Reputation: 1224

Using asynchronous await on dispatch

I was tinkering around with async await in react-native by making the dispatch asynchronous. Is there anything wrong or problematic with making the dispatch asynchronous as shown below? It seems to work (other than it's a polyfill). If there's nothing wrong with this approach, I'm thinking it could work quite nice for react-native.

export function fetchData(date, lng, lat){
  const {year, month} = date;
  return async(dispatch) => {
    dispatch(requestData())
    try {
      const data = await request(`http://data.police.uk/api/crimes-street/all-crime?lat=${lat}&lng=${lng}&date=${year}-${month}`)
      dispatch(recieveData(data))
    } catch (err) {
      dispatch(requestError(err))
    }
  }
} 

Upvotes: 4

Views: 18269

Answers (2)

Оlexandr Pilipenko
Оlexandr Pilipenko

Reputation: 11

I use this pattern :

const result = (res) => {
        if (!res.result) {
          this.setState({
            ...this.state,
            Valid: false
          });
        }
      };


AsyncFn(this.props.dispatch, field , result);



export async function AsyncFn(dispatch, field, Callback) {
  try {
    const response = await (
      request.post(url)
    );

    if (response && response.body) {
      if (response.body.result) {
        dispatch(Auth());
        dispatch(openModal());
      } else {
        Callback(response.body);
      }
    } else {
      Callback({ result: false, message: 'Not valid' });
    }
  } catch (err) {
    Callback({ result: false, message: err.message });
  }
}

Upvotes: 1

Stephen Cleary
Stephen Cleary

Reputation: 456322

That should work quite well (assuming you have redux-thunk in your middleware). I use a similar approach (with promises rather than async/await) in several React/Redux apps.

There is a redux-promise as well, but I find it insufficient for two reasons: there's no "begin" action, and there's no way to set meta which is often necessary for asynchronous actions. So I prefer to dispatch the actions explicitly rather than the promises, as your code does.

Upvotes: 3

Related Questions