简体   繁体   English

React Axios服务类

[英]React Axios Service Class

I am using axios to handle API calls in my React/Redux application. 我正在使用axios处理我的React / Redux应用程序中的API调用。 The token is set globally. 令牌是全局设置的。

Here are some examples: 这里有些例子:

// Add Post
export const addPost = postData => dispatch => {
    dispatch(clearErrors());

    axios
        .post('/api/posts', postData)
        .then(res =>
            dispatch({
                type: ADD_POST,
                payload: res.data,
            })
        )
        .catch(err =>
            dispatch({
                type: GET_ERRORS,
                payload: err.response.data,
            })
        );
};

// Add Comment
export const addComment = (postId, commentData) => dispatch => {
    dispatch(clearErrors());

    axios
        .post(`/api/posts/comment/${postId}`, commentData)
        .then(res =>
            dispatch({
                type: GET_POST,
                payload: res.data,
            })
        )
        .catch(err =>
            dispatch({
                type: GET_ERRORS,
                payload: err.response.data,
            })
        );
};

// Get posts
export const getPosts = () => dispatch => {
    dispatch(setPostsLoading);

    axios
        .get('/api/posts')
        .then(res =>
            dispatch({
                type: GET_POSTS,
                payload: res.data,
            })
        )
        .catch(err =>
            dispatch({
                type: GET_POSTS,
                payload: null,
            })
        );
};

// Delete post
export const deletePost = id => dispatch => {
    axios
        .delete(`/api/posts/${id}`)
        .then(res =>
            dispatch({
                type: DELETE_POST,
                payload: id,
            })
        )
        .catch(err =>
            dispatch({
                type: GET_ERRORS,
                payload: err.response.data,
            })
        );
};

Could you please tell me, what's the best way to handle such API calls in a scalable app? 您能否告诉我,在可伸缩应用程序中处理此类API调用的最佳方法是什么? Maybe, there's an example of Axios wrapper/service class to ease it and not to write the same logic every time? 也许,有一个Axios包装器/服务类的示例可以简化它,而不是每次都编写相同的逻辑?

Thanks! 谢谢!

You can easily use a small curried function for that: 您可以轻松地使用一个小的咖喱函数:

 const api = (url, type, errorType) => postData => dispatch => {
  dispatch(clearErrors());

  axios
    .post(url, postData)
    .then(res =>
        dispatch({
            type,
            payload: res.data,
        })
    )
    .catch(err =>
        dispatch({
            type: errorType,
            payload: err.response.data,
        })
    );
};

That can then be used as: 然后可以用作:

export const addPost = api("api/post", ADD_POST, GET_ERRORS);

 export const addComment = (postId, data) => api(`/api/posts/comment/${postId}`, ADD_COMMENT, GET_ERRORS)(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM