Redux - how to call an action and wait until it is resolved

前端 未结 2 491
鱼传尺愫
鱼传尺愫 2021-01-05 17:24

I\'m using react native + redux + redux-thunk I do not have much experience with redux and react native

I\'m calling an action inside my component.

         


        
相关标签:
2条回答
  • 2021-01-05 18:09

    I don't understand the problem, but maybe this could help

    export const checkClient = (cliente) => {
      return dispatch => {
        dispatch({type: CHECK_CLIENT_PENDING });
    
        axios.get(`${API_HOST}/api/checkclient`, header).then(response => {
    
            dispatch({type: CHECK_CLIENT, payload: response.data }); //valid or invalid
    
        }).catch((error) => {  });
    
       }
    }
    

    ...


     this.props.checkClient(cliente);
    
     if(this.props.clienteIsPending){
      ...
     }
    
     if(this.props.clienteIsValid){
      ...
     }
    
    0 讨论(0)
  • 2021-01-05 18:17

    You can return a promise from the action, so that the call becomes thenable:

    // Action
    export const checkClient = (cliente) => {
        return dispatch => {
            // Return the promise
            return axios.get(...).then(res => {
                ...
                // Return something
                return true;
            }).catch((error) => {  });
        }
    }
    
    
    class MyComponent extends React.Component {
    
        // Example
        componentDidMount() {
            this.props.checkClient(cliente)
                .then(result => {
                    // The checkClient call is now done!
                    console.log(`success: ${result}`);
    
                    // Do something
                })
        }
    }
    
    // Connect and bind the action creators
    export default connect(null, { checkClient })(MyComponent);
    

    This might be out of scope of the question, but if you like you can use async await instead of then to handle your promise:

    async componentDidMount() {
        try {
            const result = await this.props.checkClient(cliente);
            // The checkClient call is now done!
            console.log(`success: ${result}`)
    
            // Do something
        } catch (err) {
            ...
        }
    }
    

    This does the same thing.

    0 讨论(0)
提交回复
热议问题