how to async/await redux-thunk actions?

后端 未结 4 1753
耶瑟儿~
耶瑟儿~ 2020-12-08 04:37

action.js

export function getLoginStatus() {
  return async(dispatch) => {
    let token = await getOAuthToken();
    let success = await verifyToken(toke         


        
4条回答
  •  时光取名叫无心
    2020-12-08 04:47

    Another remix for async await redux/thunk. I just find this a bit more maintainable and readable when coding a Thunk (a function that wraps an expression to delay its evaluation ~ redux-thunk )

    actions.js

    import axios from 'axios'
    export const FETCHING_DATA = 'FETCHING_DATA'
    export const SET_SOME_DATA = 'SET_SOME_DATA'
    
    export const myAction = url => {
      return dispatch => {
        dispatch({
          type: FETCHING_DATA,
          fetching: true
        })
        getSomeAsyncData(dispatch, url)
      }
    }
    
    async function getSomeAsyncData(dispatch, url) {
      try {
        const data = await axios.get(url).then(res => res.data)
        dispatch({
          type: SET_SOME_DATA,
          data: data
        })
      } catch (err) {
        dispatch({
          type: SET_SOME_DATA,
          data: null
        })
      }
      dispatch({
        type: FETCHING_DATA,
        fetching: false
      })
    }
    

    reducers.js

    import { FETCHING_DATA, SET_SOME_DATA } from './actions'
    
    export const fetching = (state = null, action) => {
      switch (action.type) {
        case FETCHING_DATA:
          return action.fetching
        default:
          return state
      }
    }
    
    export const data = (state = null, action) => {
      switch (action.type) {
        case SET_SOME_DATA:
          return action.data
        default:
          return state
      }
    }
    

提交回复
热议问题