I am stuck on a issue involving adding a listener for Flux store properties. I am bouncing around the web for guidance and this has now been a circle that does not end.
My changeListener is not working and I am not sure why.
My code is as follows:
AppStore
imports...
const name = 'CHANGE';
class AppStore extends EventEmitter {
constructor() {
super();
this.data = {
isLoading: { flag: false, content: '' }
}
dispatcher.register(this.registerToActions.bind(this));
}
registerToActions(action) {
switch (action.actionType) {
case STORE_CONST.loader:
this.setLoader(action.payload);
break;
...
}
// persist changes into store
this.emit(name);
}
...
setLoader(data) {
let loader = this.data.isLoading;
loader.flag = data.flag;
loader.content = data.content;
}
addChangeListener(callback) {
this.on(name, callback);
}
removeChangeListener(callback) {
this.removeListener(name, callback);
}
getAll() {
return this.data;
}
}
const appStore = new AppStore();
export default appStore;
Store Usage
import...
const initialState = {
globalStore: appStore.getAll()
};
export class Omega extends Component {
constructor(props) {
super(props);
this.state = initialState;
...
}
onChange() {
this.setState({globalStore: appStore.getAll()});
}
componentDidMount() {
appStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
appStore.removeChangeListener(this.onChange);
}
...
...
}
Any advise what am I doing wrong. Thanks in advance!
I managed to resolve the issue, though I am not sure why it was not working and is now working.
In AppStore, the code below:
I simply moved this.emit(name) out and added it directly to setLoader function, as shown below:
Like I said, I do not know why it works after this fix.