JeePing
JeePing

Reputation: 489

Dynamic react state

I'm currently learning React and I want to implement a dynamic state system with my WebSockets connection. So I did a basic event listener system. Here's my code:

class UIEvents {
    constructor() {
        this.Events = {};
    }

    BindEvent(name, cb) {
        if(!this.Events[name]) {
            this.Events[name] = [];
        }

        this.Events[name].push(cb);
    }

    CallEvent(name, value) {
        if(!this.Events[name]) {
            return console.error("Event is not registred");
        }

        for(var cb of this.Events[name]) {
            cb(value);
        }
    }
} 

var EventManager = new UIEvents();

class Welcome extends React.Component {
    constructor() {
        super();
        EventManager.BindEvent("name", this.onName)
    }

    getInitialState = () => {
        return {
            name: "Haha"
        }
    }

    onName = (name) => {
        console.log("Replace??", name)
        this.setState({
            name: name
        })
    }

    render() {
        return <h1>Hello, {this.state.name}</h1>;
    }
}

function App() {
  return (
    <div>
      <Welcome />
      <Welcome />
      <Welcome />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

EventManager.CallEvent("name", "Michel")

However, I have this error

pen.js:54 Uncaught TypeError: Cannot read property 'name' of null
    at Welcome.render (pen.js:54)
    at p._renderValidatedComponentWithoutOwnerOrContext (react.min.js:13)
    at p._renderValidatedComponent (react.min.js:13)
    at performInitialMount (react.min.js:13)
    at p.mountComponent (react.min.js:13)
    at Object.mountComponent (react.min.js:15)
    at h.mountChildren (react.min.js:14)
    at h._createInitialChildren (react.min.js:13)
    at h.mountComponent (react.min.js:13)
    at Object.mountComponent (react.min.js:15)

This code is supposed to I don't understand what is wrong.

Codepen demo

Upvotes: 0

Views: 179

Answers (1)

vijayst
vijayst

Reputation: 21846

If the React component is based on ES6 class, the initial state should be set in the constructor.

constructor() {
  super();
  EventManager.BindEvent("name", this.onName);
  this.state = { name: 'Haha' };
}

Upvotes: 3

Related Questions