Often with reusable components, the logic needs to be adjusted to handle various use cases. Rather than filling our component event handlers with if
statements and loading our state
with one-off properties, we can expose our state
directly to users of our reusable component in a way that's flexible and simple with a state reducer.
Nice. Why do you need state
argument in the toggleStateReducer if you do not use it?
Hi Viktor,
The Toggle example that we're using in this course is great, but it's not entirely practical. In a more real-world component, having the state
can be useful. For example, some of the examples here use a state reducer (you can see the state reducers in the shared.js
file) and one of them references the state
: https://codesandbox.io/s/924217jvro
Thanks for that.
state argument in the toggleState reducer is called from toggle Component and not useful for Switch Component. The properties associated in that state are from toggle component.
Hi Kent, Could you explain where timesClicked is stored - console does not print this somehow? I am trying to show timesClicked in console from handleToggle:
handleToggle = (...args) => {
this.setState(mystate => {
console.log(mystate)
let {timesClicked} = mystate
return {
timesClicked: timesClicked + 1,
}
})
this.props.onToggle(...args)
}```
(https://codesandbox.io/s/rwp5z49qo4)
console does not print this somehow?
It seems to be printing it fine for me. You can learn more about the state updater function in the setState
docs. I hope that's helpful.
Thanks for your input, I'm not sure what I did the other day that broke things.
You know, I may be somehow hindered but it all seems overly complex to do something so simple. I know react is all about functional programming (and this might be my disability to do FP proficiently) but still - introducing a new API for setting the state seems like the worst thing to do because it defies the least-surprise principle.