Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  6] [ 3]  / answers: 1 / hits: 25776  / 8 Years ago, thu, february 25, 2016, 12:00:00

I use the following pattern in several components throughout my app. I notice that many people discourage using forceUpdate(), and some even call it a hack. So how should this be done without using it?



// user.js

export default class User extends EventEmitter {
constructor(args) {
super();
this.id = args.id;
this.isActivated = args.isActivated || false;
}
activate() {
this.isActivated = true;
this.emit('change');
}
}

// UserView.jsx

export default class UserView extends React.Component {
componentDidMount() {
this.props.user.on('change', this.onUserUpdate);
}
onUserUpdate() {
this.forceUpdate();
}
render (
var user = this.props.user;
return (
<div>
<span>User {user.isActivated ? 'is' : 'is not'} activated.</span>
<button onClick={user.activate()}>Activate</button>
</div>
);
);
}

// app.js

var user = new User({ id: 123 });
ReactDOM.render(<UserView user={user} />, container);

More From » reactjs

 Answers
151

Solved using MobX, a reactive paradigm that makes state observable and automatically upates observing components.



https://github.com/mobxjs/mobx


[#63168] Tuesday, February 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
malkajillc

Total Points: 652
Total Questions: 107
Total Answers: 98

Location: Finland
Member since Sat, Nov 6, 2021
3 Years ago
malkajillc questions
;