Last active
February 26, 2021 12:50
-
-
Save vinayakkulkarni/bf79a98188db4ae2d0722688a5a56579 to your computer and use it in GitHub Desktop.
Demo.vue
This file contains 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
<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> |
This file contains 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
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