Enums in React
I wrote a component that held an Enum, made in the popularly-recommended fashion, as state:
const MyEnum = Object.freeze({
FOO: Symbol('foo'),
BAR: Symbol('bar'),
})
class MyThing extends Component {
constructor(props) {
super(props)
this.state = { enumValue = MyEnum.FOO }
}
render() {
return({
this.state.enumValue === MyEnum.FOO ?
<p>I pity the foo</p> :
this.state.enumValue === MyEnum.BAR ?
<p>I pity the bar</p> :
<p>I pity myself</p>
})
}
}
and suddenly my app was breaking on hot-reloads, and I had written pitiably broken code! It seemed like the state was somehow becoming invalid whenever a hot reload happened.
This is because the hot reloader preserves the state, but every time the component is reloaded, our ES6 engine generates a new unique value for each Symbol
, so the comparison this.state.enumValue === MyEnum.FOO
is comparing an old value of MyEnum.FOO
to the current one, yeilding false
. So use an enum with deterministic values, like, say,
const MyEnum = Object.freeze({
FOO: Symbol.for('foo'),
BAR: Symbol.for('bar'),
})