Jan Jan - 1 month ago 20
Javascript Question

Returning promise from dispatch

Here is my action:

export function fetchNearbyUsers(user, position) {
return (dispatch) => {
const query = new Parse.Query(Parse.User);
query.withinKilometers('location', createGeoPoint(position), 10);
query.equalTo('gender', user.attributes.interest);
query.notEqualTo('objectId', user.id);
query.limit(15);
return query.find().then((users) => {
dispatch({ type: GET_NEARBYUSER_LIST, payload: users });
return Promise.resolve();
}).catch((error) => {

});
};
}


now the question is why does this return undefined, when i map my dispatch through connect.

this.props.fetchNearbyUsers(this.props.user, this.props.location).then(() => {
this.setState({ refreshing: false });
}).catch((error) => {

});

const mapDispatchToProps = dispatch => ({
fetchNearbyUsers: (user, position) => {
dispatch(fetchNearbyUsers(user, position));
},
});


as to this returns the Promise when i am accessing the store through context:

const { dispatch } = this.context.store;
this.setState({ refreshing: true });
dispatch(fetchNearbyUsers(this.props.user, this.props.location)).then(() => {
this.setState({ refreshing: false });
});

Answer

The way arrow functions work:

var addOne = (arg) => arg+1;

addOne returns arg plus 1, there's an implied return - this is shorthand for

var addOne = (arg) => {
    return arg+1;
}

note, if you use {} in arrow function body, there's no longer an implied return

So - your code needs to be

const mapDispatchToProps = dispatch => ({
  fetchNearbyUsers: (user, position) => {
    return dispatch(fetchNearbyUsers(user, position));
  }
});

or

const mapDispatchToProps = dispatch => ({
  fetchNearbyUsers: (user, position) => 
    dispatch(fetchNearbyUsers(user, position))
});

or

const mapDispatchToProps = dispatch => ({
  fetchNearbyUsers: (user, position) => dispatch(fetchNearbyUsers(user, position))
});