react-model
react-model copied to clipboard
how to display a loading indicator on fetch calls
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.
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)