react.js:使用redux-form,rest api和async / await创建资源

时间:2018-01-25 19:08:35

标签: javascript reactjs redux redux-form redux-thunk

我尝试使用redux格式和REST api创建新资源。

我发送createPost操作,我想在继续之前检查帖子是否成功。

const handleFormSubmit = (values, dispatch) => {
    dispatch(createPost(values));
    //I want to check here if post was succeeded.
    //if status = 200 this.props.history.push('/');
}


export function createPost(values) {
  return async function(dispatch) {
    let request;
    try {
      request = await axios.post(`${ROOT_URL}/posts`, values)
    } catch(err) {
      request = { err };
    }
    dispatch({
      type: CREATE_POST,
      payload: request
    })    
  }
}

2 个答案:

答案 0 :(得分:0)

返回一个承诺,如下:

export function createPost(values) {
  return function(dispatch) {
    return new Promise( async function(resolve, reject){
      let request;
      try {
        request = await axios.post(`${ROOT_URL}/posts`, values)
      } catch(err) {
        reject(err)
      }
      dispatch({
        type: CREATE_POST,
        payload: request
      }) 
      resolve(request)
    })
  }   
}

   const handleFormSubmit = () => {
        dispatch(createPost(values))
        .then( res => {
          // do yoour stuff on succes
        } )
        .catch(err => {
          // stuff on err
        }) 
    }

答案 1 :(得分:0)

在看到您的密码时,我认为您不需要使用承诺。 请尝试以下方式:

const getAction = (values) => (dispatch) => {
  return axios
          .post(`${ROOT_URL}/posts`, values)
          .then(
            () => {
              dispatch({
                type: CREATE_POST,
                payload: request
              })
            },
            () => {
              throw new SubmissionError({
                _error: 'Failed'
              });
            }
           );
};

const handleSubmit = (values) => {
  return dispatch(getAction(values));
};