Search code examples
javascriptreactjsflux

Dispatch doesn't update component instantly


For reference I'm following this tutorial. My trial app is a user management tool. Which currently shows a list of users below is the store code. It succesfully adds a user to the list using dispatcher.dispatch({type: "CREATE_USER", name: "Andrew"}). However it doesn't do so till I click on a route then it updates.

    import { EventEmitter } from "events";

    import dispatcher from "../Dispatcher";

    class UserManagement extends EventEmitter{
        constructor(){
            super();
            this.users =
                [
                {
                    id: 1234,
                    name: 'Anton',
                    email: '[email protected]'
                },
                {
                    id: 12345,
                    name: 'Bacon',
                    email: '[email protected]'
                }
                ];
        }
        getAll(){
            return this.users;
        }
        createUser(name){
            const id = Date.now();
            this.users.push({
                id,
                name,
                email: '[email protected]'
            });
            this.emit("change");
        }

        handleActions(action){
            switch(action.type){
                case "CREATE_USER":{
                    this.createUser(action.name);
                    break;
                }
            }
        }
    }
    const userobj = new UserManagement;
    dispatcher.register(userobj.handleActions.bind(userobj));
    window.dispatcher = dispatcher;

    export default userobj;

EDIT I'm thinking I need to trigger a state change?


Solution

  • To re-render the data you should trigger the render by either calling setState or forcing rendering using forceUpdate

    Note that forceUpdate is not recommended, correct way for your component to read store data is to copy data into state and read from this.state in the render function.

    http://blog.andrewray.me/flux-for-stupid-people/