Skip to content

Commit

Permalink
Merge pull request #78 from soma-dalda/feat/#77
Browse files Browse the repository at this point in the history
[#77] ♻️ , 🐛 : 이슈 수정 및 리팩토링
  • Loading branch information
jaewoong2 authored Nov 3, 2022
2 parents 303906a + 6ad7243 commit 6ee26bb
Show file tree
Hide file tree
Showing 11 changed files with 104 additions and 57 deletions.
2 changes: 1 addition & 1 deletion src/hooks/useGetCompany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const useGetCompany = (options?: UseQueryOption) => {
() => getCompany({ companyDomain: domain }),
{
...options,
enabled: Boolean(domain) && options?.enabled,
enabled: domain ? options?.enabled : false,
}
)

Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useGetOrderByOrderId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const useGetOrderByOrderId = (options?: UseQueryOption) => {
() => getOrderByOrderId({ orderId: id }),
{
...options,
enabled: options?.enabled && Boolean(id),
enabled: id ? options?.enabled : false,
}
)
}
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useGetOrders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const useGetOrders = (type: 'company' | 'consumer', options?: UseQueryOption) =>
() => getConsumerOrdersByUserId(),
{
...options,
enabled: options?.enabled && Boolean(user?.id),
enabled: user?.id ? options?.enabled : false,
}
)
}
Expand Down
45 changes: 32 additions & 13 deletions src/hooks/useGetUser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { AxiosError } from 'axios'
import { useQuery, UseQueryOptions, QueryKey } from 'react-query'
import { getUser } from '@/apis/service'
import { RequestError, User } from '@/type'
Expand All @@ -10,21 +11,39 @@ type UseQueryOption = Omit<
>

const useGetUser = (options?: UseQueryOption) => {
const [value] = useLocalStorage('accessToken')
const [value, setValue, refetch] = useLocalStorage('accessToken')

return useQuery<User, RequestError>('getUser', getUser, {
...options,
enabled: options?.enabled && Boolean(value),
onError: async (error) => {
if (typeof options?.onError === 'function') {
options?.onError(error)
}
if (error.response?.status === 401) {
const res = await http.post<string>('/api/user-auth/refresh')
window.localStorage.setItem('accessToken', res.data)
}
const query = useQuery<User, RequestError>(
'getUser',
async () => {
refetch()
return getUser()
},
})
{
...options,
enabled: value ? options?.enabled : false,
onError: async (error) => {
if (typeof options?.onError === 'function') {
options?.onError(error)
}
if (error.response?.status === 401) {
try {
const res = await http.post<string>('/api/user-auth/refresh')
setValue(res.data)
} catch (err) {
setValue('')
throw new AxiosError()
}
} else {
setValue('')
}
query.remove()
},
retry: 0,
}
)

return query
}

export default useGetUser
48 changes: 28 additions & 20 deletions src/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,9 @@
import { useEffect, useState } from 'react'

const useLocalStorage = <T = string>(key: string, initialValue?: T) => {
const [storeValue, setStoreValue] = useState<T>()
const useLocalStorage = <T = string>(key: string, initialValue: T | string = '') => {
const [storeValue, setStoreValue] = useState<T | string>()

useEffect(() => {
if (typeof window === 'undefined') {
setStoreValue(initialValue)
}
try {
const prevValue = window.localStorage.getItem(key)
if (prevValue) {
setStoreValue(JSON.parse(prevValue))
} else {
setStoreValue(initialValue)
}
} catch (err) {
setStoreValue(initialValue)
}
}, [])

const setValue = (data: T | ((val?: T) => T)) => {
const setValue = (data: string | T | ((val?: T | string) => T)) => {
const value = data instanceof Function ? data(storeValue) : data

setStoreValue(value)
Expand All @@ -33,7 +17,31 @@ const useLocalStorage = <T = string>(key: string, initialValue?: T) => {
}
}

return [storeValue, setValue] as const
const refetch = () => {
if (typeof window === 'undefined') {
setValue(initialValue)
}
try {
const prevValue = window.localStorage.getItem(key)
if (prevValue) {
if (typeof prevValue === 'string') {
setValue(prevValue)
} else {
setValue(JSON.parse(prevValue))
}
} else {
setValue(initialValue)
}
} catch (err) {
setValue(initialValue)
}
}

useEffect(() => {
refetch()
}, [window.localStorage])

return [storeValue, setValue, refetch] as const
}

export default useLocalStorage
26 changes: 26 additions & 0 deletions src/hooks/useToast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { ToastOptionType, useToast as usePreviousToast } from '@jaewoong2/toast'

const useToast = (message: string, options?: ToastOptionType) => {
const suceess = usePreviousToast(message, {
backgroundColor: '#354898',
width: 200,
color: 'white',
borderRadius: 100,
...options,
})

const error = usePreviousToast(message, {
backgroundColor: '#E56FB4',
width: 200,
color: 'white',
borderRadius: 100,
...options,
})

return {
suceess,
error,
}
}

export default useToast
20 changes: 6 additions & 14 deletions src/pages/Configuration/hooks/useConfiguration.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
import useInput from '@/components/compounds/Form/hooks/useInput'
import useGetUser from '@/hooks/useGetUser'
import { useToast } from '@jaewoong2/toast'
import useToast from '@/hooks/useToast'
// import { useToast } from '@jaewoong2/toast'
import React, { useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import usePatchUser from './usePatchUser'

const useConfiguration = () => {
const [username, setUsername, onChangeUsername] = useInput()
const [userPhone, setUserPhone, onChangeUserPhone] = useInput()
const { show: successShow } = useToast('변경 완료', {
backgroundColor: '#354898',
width: 200,
color: 'white',
borderRadius: 100,
})

const { show: errorShow } = useToast('휴대폰 번호 양식을 지켜주세요 :)', {
backgroundColor: '#E56FB4',
const { suceess } = useToast('변경 완료')
const { error } = useToast('휴대폰 번호 양식을 지켜주세요 :)', {
width: 300,
color: 'white',
borderRadius: 100,
})

const { isLoading: userLoading } = useGetUser({
Expand All @@ -42,9 +34,9 @@ const useConfiguration = () => {
if (userPhone.length === 11) {
mutate({ username, userPhone })
navigate('/')
successShow()
suceess.show()
} else {
errorShow()
error.show()
}
},
[username, userPhone]
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Domain/hooks/useGetCompanyRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const useGetCompanyRequest = (options?: UseQueryOption) => {

return useQuery<Company, RequestError>(`${domain}`, () => getCompany({ companyDomain: domain }), {
...options,
enabled: Boolean(domain) && options?.enabled,
enabled: domain ? options?.enabled : false,
})
}

Expand Down
9 changes: 4 additions & 5 deletions src/pages/Edit/hooks/useEditMount.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import useGetUser from '@/hooks/useGetUser'
import { useToast } from '@jaewoong2/toast'
import useToast from '@/hooks/useToast'
import { useNavigate } from 'react-router-dom'
import useCompanyEditAction from './useCompanyEditAction'

const useEditMount = () => {
const navigate = useNavigate()
const { show } = useToast('로그인 후 이용하세요', {
type: 'warn',

const { error } = useToast('로그인 후 이용하세요', {
position: 'top',
subPosition: 'right',
color: 'white',
})

const { hanldeComapny } = useCompanyEditAction()
Expand All @@ -23,7 +22,7 @@ const useEditMount = () => {
hanldeComapny({ ...data })
},
onError: () => {
show()
error.show()
navigate(-1)
},
})
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Home/components/blocks/RecommandCards.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const RecommandCards = ({ title }: Props) => {
<div className="flex w-full gap-4 overflow-y-scroll pb-5">
{companies?.map((company) => (
<Card
key={company.id}
key={company.companyName}
companyDomain={encodeURIComponent(company.companyDomain ?? '')}
companyName={company.companyName}
profileImage={company.profileImage}
Expand Down
3 changes: 3 additions & 0 deletions src/pages/Order/context/OrderContextProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import useGetTemplate from '@/hooks/useGetTemplate'
import useStatus from '@/hooks/useStatus'
import useToast from '@/hooks/useToast'
import { Order } from '@/type'
import { useModal } from '@jaewoong2/modal'
import { AxiosError } from 'axios'
Expand All @@ -20,6 +21,7 @@ const OrderContextProvider = ({ children }: PropsWithChildren) => {
...defaultOrder,
templateId: id,
})
const { suceess } = useToast('제출 완료')

useGetTemplate(id ?? '', {
onSuccess: (data) => {
Expand Down Expand Up @@ -53,6 +55,7 @@ const OrderContextProvider = ({ children }: PropsWithChildren) => {
setCurrent(0)
setOrder({ ...defaultOrder, templateId: id })
navigate(`/${domain}`)
suceess.show()
},
onError: (err) => {
if (err.status === AxiosError.ECONNABORTED) {
Expand Down

0 comments on commit 6ee26bb

Please sign in to comment.