How can I get the response from dispatch?

I have a component which has a form where at the moment to do clic on submit button, I call a function handleSubmit (it is on my component), this function call an action through of dispatch and this action, I make a call to a service (HTTP Request).

handleSubmit

handleSubmit = (e) => {
   e.preventDefault()
   const { validateFields } = this.props.form;

   validateFields((err, params) => {
       if (!err) {
            const { user, dispatch } = this.props;

            let response = dispatch(actions.addDevice(params))
            console.log(response); //Response is undefined
       }
    });
}

actions.addDevice

function addDevice(params){
    return (dispatch, getState) => {
        let { authentication } = getState();
        dispatch(request({}));

        service.addDevice(params, authentication.user.access_token)
            .then(
                response => {
                    if(response.status === 201) {
                        dispatch(success(response.data));
                    }
                    return response;
                },
                error => {
                    dispatch(failure(error.toString()));
                    dispatch(alertActions.error(error.toString()));
                }
            )
    }

    function request(response) { return { type: constants.ADD_DEVICE_REQUEST, response } }
    function success(response) { return { type: constants.ADD_DEVICE_SUCCESS, response } }
    function failure(error) { return { type: constants.ADD_DEVICE_FAILURE, error } }
}

service.addDevice

function addDevice(params, token){
    return axios({
        url: 'http://localhost:5000/user/add-device',
        method: 'POST',
        headers: { 'Authorization': 'Bearer ' + token},
        data: {
            data1: params.data1,
            data2: params.data2,
            data3: params.data3
        }
    })
    .then(function(response) {
        return response;
    })
    .catch(function(error) {
        return error.response;
    });
}

I would like to get the response in my component to be able to make validations but as the request is async, I never can get the response and only prints an undefined variable. How can I get the response sync? Or what do I need do to be able to make validations?

You are not returning the promise service.addDevice.

So you can do return service.addDevice... and in the handleSubmit you do dispatch(...).then((data) => ...do something with the data...)

Async Actions, Usually, for any API request you'll want to dispatch at least three different kinds of You may also want to fetch in response to a route change, so it's not wise to� Since Dispatch is fullyasynchronous, countryrepresents a futureof the string ratherthan the string itself. Deferring action. You can act on the response once it’s available with afor-expression. for (c <- country) println(c) This for-expression applies to any successfulresponse that iseventually produced.

let response = dispatch(actions.addDevice(params)) 

this is asynchronous. So it is not surprising to return undefined from console.log(). console.log() execute even before dispatch process is completed. Use promise or async await syntax. I would recommend using the async-await syntax.

handleSubmit = (e) => {
   e.preventDefault()
   const { validateFields } = this.props.form;

   validateFields(async (err, params) => {
       if (!err) {
            const { user, dispatch } = this.props;

            let response =await dispatch(actions.addDevice(params))
            console.log(response); //Response is undefined
       }
    });
}

Different Ways to Dispatch Actions with Redux, The dispatch method is available on the store object. const delay = (ms) => new Promise(response => setTimeout(response, ms)) function*� You can make a difference in the emergency dispatch and response community. Share your talents and ideas to help move this profession forward. There are many ways to get involved.

Please replace your code with this code

handleSubmit

handleSubmit = (e) => {
   e.preventDefault()
   const { validateFields } = this.props.form;

   validateFields((err, params) => {
       if (!err) {
            const { user, dispatch } = this.props;

            dispatch(actions.addDevice(params)).then((response)=>{
                  console.log(response);
            })
       }
    });
}

actions.addDevice

function addDevice(params){
    return (dispatch, getState) => {
        let { authentication } = getState();
        dispatch(request({}));

        return service.addDevice(params, authentication.user.access_token)
            .then(
                response => {
                    if(response.status === 201) {
                        dispatch(success(response.data));
                    }
                    return response;
                },
                error => {
                    dispatch(failure(error.toString()));
                    dispatch(alertActions.error(error.toString()));
                }
            )
    }

    function request(response) { return { type: constants.ADD_DEVICE_REQUEST, response } }
    function success(response) { return { type: constants.ADD_DEVICE_SUCCESS, response } }
    function failure(error) { return { type: constants.ADD_DEVICE_FAILURE, error } }
}

Redux: Wrapping dispatch() to Recognize Promises from , I'm using the promise the method to transform the result of the promise from the response to the action object generated by received todos given the filter and the � Public Record, and 911 Call Logs Q: We submitted a Public Records Request to the Police Department seeking a copy of their ‘Call for Service’ log, known also as the Daily Dispatch Log, Police Blotter or 911 Call Log. They denied the request indicating that they don’t have this type of information, therefore are not […]

reduxjs/redux-thunk: Thunk middleware for Redux, The inner function receives the store methods dispatch and getState as parameters. An action creator that returns a function to perform asynchronous dispatch:. You can directly use getState in your app-thunk function by simply passing it as an argument like return (dispatch,getState) => {} and then use this getState() method to access the store. There are some other methods but these should work.

Redux-Thunk examples � GitHub, dispatch({type: "REQUEST_SUCCEEDED", payload: response});. } } // An example of conditional dispatching based on state. const MAX_TODOS = 5;. function� Forgot your username/password? Click Here: If you do not have your username and/or password, please call customer support at 1-866-894-5474.

4 ways to dispatch actions with Redux - Blogs, The response is hard to heard, but it depends of your use case ! Nevertheless, when you want to dispatch an action from your component, you should first� A smart officer will always respond swiftly and professionally to the dispatchers. For three main reasons: 1. It is radio traffic and “somebody” is always listening…

Comments
  • To use the response in your component you need to do 3 more things: Make a reducer on ADD_DEVICE_REQUEST to update the redux state, make a selector function to grab the variable you changed in the state, then add a prop to the component equal to the result of that selector with a mapStateToProps function