最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I get the response from dispatch? - Stack Overflow

programmeradmin3浏览0评论

I have a ponent which has a form where at the moment to do clic on submit button, I call a function handleSubmit (it is on my ponent), 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 ponent 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?

I have a ponent which has a form where at the moment to do clic on submit button, I call a function handleSubmit (it is on my ponent), 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 ponent 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?

Share Improve this question edited Apr 3, 2019 at 16:53 Hoose asked Apr 3, 2019 at 16:10 HooseHoose 1951 gold badge2 silver badges11 bronze badges 1
  • To use the response in your ponent 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 ponent equal to the result of that selector with a mapStateToProps function – WilliamNHarvey Commented Apr 3, 2019 at 16:35
Add a ment  | 

3 Answers 3

Reset to default 4

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...)

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 pleted. Use promise or async await syntax. I would remend 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
       }
    });
}

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 } }
}
发布评论

评论列表(0)

  1. 暂无评论