create hooks

This commit is contained in:
DuvCharles 2022-12-14 15:14:24 +01:00 committed by Hadrien Lucas
parent f92d823d1e
commit fea72c36f5
3 changed files with 72 additions and 11 deletions

View File

@ -1,16 +1,49 @@
import { MutationHook } from '@vercel/commerce/utils/types'
import useLogin, { UseLogin } from '@vercel/commerce/auth/use-login'
import { useCallback } from 'react'
import useCustomer from '@vercel/commerce/customer/use-customer'
import { setCustomerToken } from '../utils/token/customer-token'
import { setCustomerId } from '../utils/token/customer-id'
export default useLogin as UseLogin<typeof handler>
export const handler: MutationHook<any> = {
fetchOptions: {
query: '',
url: '/authentication-token',
method: 'POST',
},
async fetcher() {
fetcher: async ({ input: { email, password }, options, fetch }) => {
const authReturn = await fetch({
url: options.url,
method: options.method,
body: {
email: email,
password: password,
},
variables: {
useToken: false,
},
})
setCustomerToken(authReturn.token)
console.log(authReturn)
const custumerRouteParts = authReturn.customer.split('/')
console.log(custumerRouteParts)
setCustomerId(custumerRouteParts[5])
return null
},
useHook: () => () => {
return async function () {}
},
useHook:
({ fetch }) =>
() => {
const { mutate } = useCustomer()
return useCallback(
async function login(input) {
const data = await fetch({ input })
await mutate()
return data
},
[fetch, mutate]
)
},
}

View File

@ -2,16 +2,32 @@ import { SWRHook } from '@vercel/commerce/utils/types'
import useCustomer, {
UseCustomer,
} from '@vercel/commerce/customer/use-customer'
import { getCustomerId } from '../utils/token/customer-id'
import { normalizeCustomer } from '../utils/normalize/normalize-customer'
export default useCustomer as UseCustomer<typeof handler>
export const handler: SWRHook<any> = {
fetchOptions: {
query: '',
url: `/customers/`,
method: 'GET',
},
async fetcher({ input, options, fetch }) {},
useHook: () => () => {
return async function addItem() {
return {}
}
fetcher: async ({ options, fetch }) => {
const syliusCustomer = await fetch({
url: options.url! + getCustomerId(),
method: options.method,
})
const customer = normalizeCustomer(syliusCustomer)
return customer
},
useHook:
({ useData }) =>
(input) => {
return useData({
swrOptions: {
revalidateOnFocus: false,
...input?.swrOptions,
},
})
},
}

View File

@ -0,0 +1,12 @@
import { SYLIUS_CUSTOMER_TOKEN } from '../../const'
export const getCustomerToken = () =>
localStorage.getItem(SYLIUS_CUSTOMER_TOKEN)
export const setCustomerToken = (token: string | null) => {
if (!token) {
localStorage.removeItem(SYLIUS_CUSTOMER_TOKEN)
} else {
localStorage.setItem(SYLIUS_CUSTOMER_TOKEN, token)
}
}