I am using the Alt library in my React/Flux project to represent the Flux part and I got to actions creators.
I created the following action:
// alt.js
import Alt from 'alt';
export default new Alt();
// UserActions.js
import alt from '../alt';
class UserActions {
constructor() {
this.generateActions(
'getUsersSuccess',
'getUsersFailed'
);
}
getUsers(userId) {
$.ajax({ url: '/api/users/'+userId })
.done((data) => {
this.actions.getUsersSuccess(data);
})
.fail((jqXhr) => {
this.actions.getUsersFailed(jqXhr);
});
}
}
export default alt.createActions(UserActions);
The problem is the actions, this.actions
, are undefined. Do I understand it correctly, that the this.generateActions
function should populate the actions
property of the UserActions
class, or do I need to write something else in order to have the actions available?
I believe, using ES6, the this
inside the anonymous functions should be correctly tied to this
of the UserActions
class.
I don't know if the implementation of Alt has changed recently, but I had to manually code the actions with dispatch, in order to get it working, and call these functions directly instead of trying to access them using the actions
property.
This is the code I have got, which can successfuly be loaded to store and maps the actions the way they should be mapped.
import alt from '../alt';
class UserActions{
getUsers(userId) {
$.ajax({url: 'api/users/'+userId})
.done((data) => {
this.getUsersSuccess(data);
})
.fail((jqHxr) => {
this.getUsersFail(jqHxr);
});
return false;
}
getUsersSuccess(data) {
return (dispatch) => {
dispatch(data);
}
}
getUsersFail(jqHxr) {
return (dispatch) => {
dispatch(jqHxr);
}
}
}
export default alt.createActions(UserActions);
With this approach the generateActions
call in constructor is not only unnecessary, but needs to be avoided, otherwise the store using this action creator will not know which action you want to use.
I also added the return false
at the end of the getUsers
function to supress console warning thrown by alt (false must be returned when a function does not dispatch).
The dispatched actions here, getUsersSuccess
and getUsersFail
, should then have counterparts in the store which consumes the parameter/parameters and affects state.