Skip to content

Instantly share code, notes, and snippets.

@MartinMalinda
Created July 12, 2020 15:48
Show Gist options
  • Save MartinMalinda/8806d1621da2ecd806191ca568b3d080 to your computer and use it in GitHub Desktop.
Save MartinMalinda/8806d1621da2ecd806191ca568b3d080 to your computer and use it in GitHub Desktop.
// 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 };
}
});
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