const disabled = (state = true, action) => {
return action.type === "TOGGLE" ? !state : state;
};
class Button extends React.Component {
render() {
const { props } = this;
console.log("rendering", props.value);
return (
<div>
<input
type="checkbox"
onClick={() => {
props.toggle().then(() => {
console.log("This will be called after re-render");
this.ref.focus();
});
console.log("This will be called before re-render");
}}
/>
<input
disabled={props.disabled}
ref={ref => {
this.ref = ref;
}}
/>
</div>
);
}
}
const toggle = () => ({
type: "TOGGLE"
});
const A = connect(
state => ({ disabled: state }),
dispatch => ({
toggle: () => {
dispatch(toggle());
return Promise.resolve();
}
})
)(Button);
const App = () => (
<Provider store={createStore(disabled, applyMiddleware(thunk))}>
<A />
</Provider>
);
In the above code, this.ref.focus() must be called only after the component re-renders, as an input with disabled prop cannot be focused.
I return a Promise in the action dispatcher function, and it seems like the Promise only gets resolved after the re-rendering caused by the dispatched action.
Why does this work and is it a guarantee?
If not, how should I make sure the code only executes after re-rendering has been triggered by the action, without adding extra middleware like redux-promise or doing it in componentDidUpdate?
Sebastian
I'm not quite sure what you want to archive. You change props and/or state which causes a render. It's not a good idea to trigger things based on render calls because every change of props and state causes a render which can be a very high amount.
Better manipulate props and state and in render you only handle the result. This way it's pretty reliable.
I took your code you posted and the one you referenced in the sandbox and changed it the way I think it should look like.
In this example, you don't even need a middleware like thunk.
codesandbox.io/s/8zw3x97q6j
I made no use of the after click variable because there are just two values. The past (pre-click) one and the current one.
In the second example I made use of thunk to dispatch an action and call a callback afterwards. This is where thunk comes into play to enable this kind of action. Without thunk we can just dispatch objects.
codesandbox.io/s/l51p0kv77l
Feel free to fork it and if you have questions, please post :).