react-model icon indicating copy to clipboard operation
react-model copied to clipboard

how to display a loading indicator on fetch calls

Open tianyingchun opened this issue 4 years ago • 1 comments

When you are developing your web application, you have to perform asynchronous operations,

e.g. perform a fetch/ajax call to obtain data from the server. Sometimes you need to do silent background operations,

whereas in other cases you need to block the user interface or notify them that something is going on.

tianyingchun avatar Aug 13 '20 08:08 tianyingchun

const initialState = {
  loading: false,
  response: {}
}

interface StateType {
  loading: boolean
  response: {
    code?: number
    data?: object
  }
}

interface ActionsParamType {
  setLoadingState: boolean
  fetchData: undefined
}

const model: ModelType<StateType, ActionsParamType> = {
  actions: {
    setLoadingState: async (payload) => {
      return {
        loading: payload
      }
    },
    fetch: async (_, { state, actions }) => {
      await actions.setLoadingState(true) // You can use other actions within the model
      const response = await fetch('https://xxx.com')
      // Solution 1: await actions.setLoadingState(false)
      // Solution 2: use subscribe api to setLoadingState after action finished
      return { light: !state.light }
    }
  },
  state: initialState
}

export default Model(model)

ArrayZoneYour avatar Aug 18 '20 03:08 ArrayZoneYour