Reputation: 266
I'm fairly new to Redux and am experiencing some behavior I don't quite understand.
I have another function nextFiveDays
that calls the exact same action but this is fired with a button click. When the button is clicked, I do see the action.type is UPDATE_DATE
dispatched and the store is updated.
In the function nextFiveDays
, the action is dispatched even if the updateDate
function is commented out. It seems setState
still triggers the action to be dispatched. Why is that?
class SomeComponent {
state = { date: new Date() }
nextFiveDays = () => {
let date = new Date(this.state.date);
date.setDate(date.getDate() + 5);
//updateDate(date); // Redux store action dispatch
this.setState({ date });
};
prevFiveDays = () => {
let date = new Date(this.state.date);
date.setDate(date.getDate() - 5);
//updateDate(date); // Redux store action dispatch
this.setState({ date });
};
render() {
const { date } = this.state
return <SemanticDatepicker
value={new Date(date)}
date={new Date(date)}
onChange={(_, data: any) => {
this.setState({ date: data.value });
updateDate(data.value);
}}
/>
<Button
onClick={this.prevFiveDays}
/>
<Button
onClick={this.nextFiveDays}
/>
}
Upvotes: 2
Views: 234
Reputation: 5972
When you call the nextFiveDays
function, it will update the date
state and will re-render the component.
You set the value of SemanticDatePicker
with this date
state value so it triggers onChange
event.
You dispatch the action inside onChange
event handler.
This is why the action is dispatched.
Note:
Redux Action can be tied into props
of the component but nothing related to component's state.
Solution:
Currently, you are updating the component's state and redux store with same value.
You can remove your date
state value and map the property from your store to the component props. (using mapStateToProps
)
So just dispatching the action will persist your date
value from your store to the component.
Upvotes: 2