goatslacker / alt

Isomorphic flux implementation
http://alt.js.org/
3.45k stars 322 forks source link

Async samples from Docs (Error) #682

Open xxRockOnxx opened 7 years ago

xxRockOnxx commented 7 years ago

I'm following the guide from here: http://alt.js.org/guide/async/

This part:

fetchLocations() {
  return (dispatch) => {
    // we dispatch an event here so we can have "loading" state.
    dispatch();
    LocationSource.fetch()
      .then((locations) => {
        // we can access other actions within our action through `this.actions`
        this.updateLocations(locations);
      })
      .catch((errorMessage) => {
        this.locationsFailed(errorMessage);
      });
    }
}
locationsFailed(errorMessage) {
  return errorMessage;
}

The dispatch() above LocationSource.fetch() returns the error.

Here's how I do my promise:


class Source{

    fetch(id){
        return new Promise(function(resolve, reject){
            $.ajax({
                url: '/source/'+id,
                success: (response) => resolve(response),
                error: () => {
                  console.error('Fetching source failed. Please check API response.');
                  reject();
                }
            })
        });
    }

}

export default new Source()

Also in here:

class LocationActions {
  updateLocationThatDoesItAsync(city) {
    return (dispatch) => {
      setTimeout(() => dispatch(city));
    };
  }
}

what i the dispatch doing on the setTImeOut? Isn't that will tell that the async request is complete? Where's the setting/dispatching of "loading" or "will fetch" state here?

edgeadjei commented 7 years ago

I'm experiencing the same issue. What is the proper way to dispatch during an asynchronous request?

getUsersList() {
    return () => {
      axios.get("api/users")
      .then((users) => {
        this.successfullyRetreivedUsers(users.data);
      })
      .catch((err) => {
        this.errorRetreivingUsers(err);
      });
    };
  }
successfullyRetreivedUsers(users){
    return users;
  }
  errorRetreivingUsers(err){
    return err;
  }
Zhythero commented 7 years ago

Weirdly, the documentation is a bit misleading.

Instead of having dispatch() at the beginning of the function as shown here

return (dispatch) => {
    // we dispatch an event here so we can have "loading" state.
    dispatch();

We should be using dispatch() after the Promise has resolved.

So I used this:

fetchUsers() {
  return dispatch => {
      axios.get('/path/to/resource').then((response) => {
        dispatch(response.data);
      }).catch((errors) => {/* handle errors */});
    }
}

the dispatch() comes with a payload parameter.

I, then, listened to the fetchUsers directly at my store

handleFetchUsers: UserActions.FETCH_USERS

then

handleFetchUsers(users) {
  this.users= users;
}
edgeadjei commented 7 years ago

Thank you for the response. Due to the inconsistent documentation and non-pluggable nature of Alt I ended up moving to Redux.