I'm using ReactJs + flux. In my store I have a method - getCurrentEvents(key)
.It recieves key and creates array of objects correctly. After that it emitts change.
I have component-list, which has handler. This handler answers to store change and calls method displayEvents()
. This method updates component's state. This conception works but not correctly. When I call getCurrentEvents(key)
it begins updating EventList-component
and doesn't stop, as a result tab in browser freezes.As I understand I got something like limitless cycle of updates, I think that something wrong is in component's methods, but I can't understand where is the mistake. How to fix this bug?
store code:
class EventStore extends EventEmitter {
constructor() {
super();
this.events = [{
id: 1,
title: 'title 1',
date: '2017-04-11 09:14:01'
}, {
id: 2,
title: 'title 2',
date: '2017-04-11 09:24:01'
}, {
id: 3,
title: 'title 3',
date: '2017-04-12 09:14:01'
}, {
id: 4,
title: 'title 4',
date: '2017-11-12 19:14:01'
}, {
id: 5,
title: 'title 5',
date: '2017-06-13 19:00:01'
}
];
}
getCurrentEvents(key) {
var currentEvents = [];
for (event in this.events){
if (this.events[event].date.includes(key)) {
currentEvents.push(this.events[event]);
}
}
return currentEvents;
this.emit("change");
}
createEvent(new_event) {
this.events.push ({
title: new_event.title,
date: new_event.date
})
this.emit("change");
}
getAll() {
return this.events
}
handleActions(action) {
switch(action.type) {
case 'CREATE_EVENT' : {
this.createEvent(action.new_event);
}
case 'DISPLAY_CURRENT_EVENTS' : {
this.getCurrentEvents(action.key);
}
}
}
}
const eventStore = new EventStore;
dispatcher.register(eventStore.handleActions.bind(eventStore))
export default eventStore;
EventList component code:
export default class EventList extends React.Component {
constructor () {
super();
this.state = {
events: EventStore.getCurrentEvents()
};
this.displayEvents = this.displayEvents.bind(this);
}
componentWillMount() {
EventStore.on("change", this.displayEvents)
}
displayEvents() {
this.setState ({
events: EventStore.getCurrentEvents()
})
}
render() {
console.log('form events LIST', this.state)
const events = this.state.events ;
var EventsList = [];
for (event in events) {
EventsList.push(
<li key={events[event].id} id={events[event].id}>
{events[event].title} , {events[event].date}
</li>
)
}
return (
<div className="">
<h3> Events on this day </h3>
<ul className="event-list-wrapper">
{EventsList}
</ul>
</div>
);
}
}
Looks like it's because the getCurrentEvents(key)
function is emitting a 'change' which is triggering displayEvents
...which calls getCurrentEvents(key)
...which emits a 'change' event which calls displayEvents
...