Created
July 12, 2020 15:48
-
-
Save MartinMalinda/8806d1621da2ecd806191ca568b3d080 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Imported from something like api/handlers.js | |
function Users() { | |
const response = axios('/api/users'); | |
return normalizeUsersReponse(response); | |
} | |
export default defineComponent({ | |
setup() { | |
const { data, error, isLoading, run: getUsers } = useApi(Users); | |
return { data, error, isLoading, getUsers }; | |
} | |
}); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function useApi(cb = () => {}) { | |
const store = useStore(); | |
const getterName = cb.name; | |
const hasGetterName = `has${cb.name}`; | |
const setterName = `set${cb.name}`; | |
const { data, error, isLoading, run } = useAsync(async () => { | |
if (store.getters[hasGetterName]) { | |
return store.getters[getterName]; | |
} | |
const data = cb(); | |
store.commit(setterName, data); | |
return data; | |
}); | |
return { data, error, isLoading, run }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment