Redux - 簡化 async function
原始版本
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})
}
}
移除沒用到的參數
export const fetchPosts = () => {
return async function(dispatch) { // can change to arrow function
const response = await jsonPlaceholder.get('/posts')
dispatch({type:'FETCH_POSTS', payload: response})
}
}
改用 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})
}
}
移除小括號
export const fetchPosts = () => { // can merge return function
return async dispatch => {
const response = await jsonPlaceholder.get('/posts')
dispatch({type:'FETCH_POSTS', payload: response})
}
}
合併 return function
export const fetchPosts = () => async dispatch => {
{ // can remove redundant
const response = await jsonPlaceholder.get('/posts')
dispatch({type:'FETCH_POSTS', payload: response})
}
}
完成
export const fetchPosts = () => async dispatch => {
const response = await jsonPlaceholder.get('/posts')
dispatch({type:'FETCH_POSTS', payload: response})
}