How to update local state of component after disptach action ?
In my case, I show a popin based on component local state :
<button onClick={() => this.setState({ popin: true })}>Open</button>
<Popin hidden={!this.state.popin}>
<form onSubmit={createItem})>
<div className="popin-heading">...</div>
<button onClick={() => this.setState({ popin: false })}>Close</button>
<button type="submit">Submit</button>
</form>
</Popin>
On submit click, createItem dispatch action catch in Saga :
function* watchCreateItem() {
yield takeEvery('CREATE_ITEM', doCreateItem);
}
function* doCreateItem(values) {
try {
// Do POST API request
const response = yield fetch('/create', { method: 'post', body: values });
// Disptach action to store new item in redux store (by reducer)
yield put(storeItem(response));
/**
* !!! Here, want to update 'state.popin = null' !!!
*/
} catch (error) {
showNotification(reponse.message, 'error');
}
}
How to close popin after API post request is success ?
I would like to keep storing popin state in local component state and not in Redux store (with mapStateToPros)
Thanks.
Finally, I add a new reducer "popin" to manage open/close state.
Action creators :
function ShowPopinAction(current = 'default') {
return { action: 'POPIN_STATE', current};
}
function HidePopinAction() {
return ShowPopinAction(null);
}
Reducer :
function (state = {current: null}, action) {
if (action.type === 'POPIN_STATE') {
return {current: action.current}
}
return state;
}
And in my component :
<button onClick={ () => ShowPopinAction('createItem') }>Open</button>
<Popin hidden={this.props.current !== 'createItem'}>
....
<button onClick={HidePopinAction}>Close</button>
</Popin>
connect(
state = > ({ current: state.popin.current }),
{ ShowPopinAction, HidePopinAction }
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With