Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger off callback after updating state in Redux?

In React, state is not be updated instantly, so we can use callback in setState(state, callback). But how to do it in Redux?

After calling the this.props.dispatch(updateState(key, value)), I need to do something with the updated state immediately.

Is there any way I can call a callback with the latest state like what I do in React?

like image 604
Brick Yang Avatar asked Sep 16 '16 06:09

Brick Yang


People also ask

What is the only way to trigger a state change in Redux?

dispatch(action)​ Dispatches an action. This is the only way to trigger a state change. The store's reducing function will be called with the current getState() result and the given action synchronously.

What happens when Redux state changes?

The only way to update a state inside a store is to dispatch an action and define a reducer function to perform tasks based on the given actions. Once dispatched, the action goes inside the reducer functions which performs the tasks and return the updated state to the store. This is what Redux is all about.

How do I call a function after dispatch?

push('/') after an action has finished dispatching to the store, this to happen when a button is pushed. Have your action creator return a promise. This way when you invoke it, you can use . then() and in your then handler you can push a new address to the history.

How do you do a callback on setState?

The setState function takes an optional callback parameter that can be used to make updates after the state is changed. This function will get called once the state has been updated, and the callback will receive the updated value of the state.


1 Answers

component should be updated to receive new props.

there are ways to achieve your goal:

1. componentDidUpdate check if value is changed, then do something..

 componentDidUpdate(prevProps){      if(prevProps.value !== this.props.value){ alert(prevProps.value) }   } 

2. redux-promise ( middleware will dispatch the resolved value of the promise)

export const updateState = (key, value)=> Promise.resolve({   type:'UPDATE_STATE',   key, value }) 

then in component

this.props.dispatch(updateState(key, value)).then(()=>{    alert(this.props.value) }) 

2. redux-thunk

export const updateState = (key, value) => dispatch => {   dispatch({     type: 'UPDATE_STATE',     key,     value,   });   return Promise.resolve(); }; 

then in component

this.props.dispatch(updateState(key, value)).then(()=>{    alert(this.props.value) }) 
like image 185
Kokovin Vladislav Avatar answered Sep 19 '22 14:09

Kokovin Vladislav