redux - shorten an async function

Origin version
export const fetchPosts = () => {
    // dispatch: can change any data we want
    // getState: get or access any data we want
    return async function(dispatch, getState) { // can remove unused parameter
        const response = await jsonPlaceholder.get('/posts')

        dispatch({type:'FETCH_POSTS', payload: response})
    }
}

Remove unused parameter
export const fetchPosts = () => {
    return async function(dispatch) { // can change to arrow function
        const response = await jsonPlaceholder.get('/posts')

        dispatch({type:'FETCH_POSTS', payload: response})
    }
}

Apply arrow function
export const fetchPosts = () => {
    return async (dispatch) => { // can remove round brackets because only one parameter
        const response = await jsonPlaceholder.get('/posts')

        dispatch({type:'FETCH_POSTS', payload: response})
    }
}

Remove round brackets
export const fetchPosts = () => { // can merge return function
    return async dispatch => {
        const response = await jsonPlaceholder.get('/posts')

        dispatch({type:'FETCH_POSTS', payload: response})
    }
}

Merge return function
export const fetchPosts = () => async dispatch => {
    { // can remove redundant 
        const response = await jsonPlaceholder.get('/posts')

        dispatch({type:'FETCH_POSTS', payload: response})
    }
}

Done
export const fetchPosts = () => async dispatch => {
    const response = await jsonPlaceholder.get('/posts')

    dispatch({type:'FETCH_POSTS', payload: response})
}


沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...