Skip to content

Instantly share code, notes, and snippets.

@vinayakkulkarni
Last active February 26, 2021 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinayakkulkarni/bf79a98188db4ae2d0722688a5a56579 to your computer and use it in GitHub Desktop.
Save vinayakkulkarni/bf79a98188db4ae2d0722688a5a56579 to your computer and use it in GitHub Desktop.
Demo.vue
<script lang="ts">
import { useProfile } from '@/hooks/profile';
import { useContext } from '@nuxtjs/composition-api';
export default defineComponent({
setup() {
const { $axios } = useContext();
const { getUser, profile } = useProfile($axios);
return { profile };
}
})
</script>
import { Auth } from '@nuxtjs/auth';
import { NuxtAxiosInstance } from '@nuxtjs/axios';
import { computed, reactive } from '@nuxtjs/composition-api';
import { Profile } from '../@types/interfaces/profile';
import { User } from '../@types/interfaces/user';
let $axios: NuxtAxiosInstance;
export function useProfile(axios: NuxtAxiosInstance, auth: Auth) {
$axios = axios;
const state = reactive({
user: {} as User.Details,
profile: {} as Profile.Details,
profileLoading: false as boolean,
});
/**
* Fetches User data from API
* @returns {void} Promise
*/
async function getUser(): Promise<void> {
if (!state.profileLoading) {
state.profileLoading = true;
state.user = await fetchUser(auth?.user?.id);
state.profile = {
name: state.user.name,
email: state.user.email,
contact: state.user.contact,
companyName: state.user.companyName,
};
state.profileLoading = false;
}
}
return {
user: computed(() => state.user),
profile: computed(() => state.profile),
profileLoading: computed(() => state.profileLoading),
getUser,
};
}
/**
* get /users/:id API &
* returns Promise resolution with User typed data
* @argument userId: string
* @returns Promise<User>
*/
async function fetchUser(userId: string): Promise<User.Details> {
return await $axios
.get(`/users/${userId}`)
.then(({ data }: { data: any }) => {
return data;
})
.catch((err: any) => {
return err;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment