byte-fe / react-model

The next generation state management library for React
236 stars 23 forks source link

how to display a loading indicator on fetch calls #164

Open tianyingchun opened 4 years ago

tianyingchun commented 4 years ago

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.

ArrayZoneYour commented 4 years ago
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)