I have a question about the following example code, which seems to have something to do with redux data flow inside.
// action.js
export function doSomething() {
return {
type : 'FOO',
data : 'BAR'
};
}
// reducer.js
...
case types.FOO :
return update(state, { mystatus : { $set : action.data } });
...
// container.js
class MyTestClass {
...
handleButtonClick() {
this.props.doSomething(); // doSomething is just simple, synchronous action creator. In this function, state.foo
console.log(this.props.status); // expected output should be 'BAR' but, actual output is 'undefined'
}
...
}
const mapStateToProps = (state => {
return {
status : state.mystatus
};
};
const mapDispatchToProps = (dispatch) => {
return {
doSomething : () => {
return dispatch(doSomthing());
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(MyTestClass);
Now, this is my question.
If you see the code 'this.props.doSomething(); console.log(this.props.status);' in handleButtonClick method, the output of this code is supposed to be 'BAR'. However, I got 'undefined'.
this.props.doSomething();
console.log(this.props.status); // output is 'undefined'
And, If I change that part like following, I could get what I expected.
this.props.doSomething();
setTimeout(() => { console.log(this.props.status); }, 0); // now output is 'BAR'!!
I thought that "calling this.props.doSomething() => creating action => dispatching => mapping the changed state to the property by redux" was a series of synchronous control flow, but it does not seem to be.
There seems to be an asynchronous control flow in the process of being dispatched.
Is it a bad idea to call a function mapped to a property and use that function's output immediately when using react-redux? Could you explain how react-redux handle this inside?
Thnak you.