main
parent
8df1fed14c
commit
1904bb8668
8 changed files with 59 additions and 91 deletions
@ -1,7 +0,0 @@ |
||||
import { User } from '../../types' |
||||
|
||||
export const mockUser: User = { |
||||
id: '4242-4242-4242-4242', |
||||
username: 'TestUser42', |
||||
email: 'testuser@email.com', |
||||
} |
@ -0,0 +1,12 @@ |
||||
import { DataBuddy } from '@dank-inc/data-buddy' |
||||
import { User } from '../../types' |
||||
|
||||
const userRecords: User[] = [ |
||||
{ |
||||
id: '42', |
||||
username: 'TestUser42', |
||||
email: 'testuser@email.com', |
||||
}, |
||||
] |
||||
|
||||
export const users = new DataBuddy(userRecords) |
@ -0,0 +1,28 @@ |
||||
import React, { createContext, useContext } from 'react' |
||||
import { Api } from '../api' |
||||
|
||||
type Props = { |
||||
children: React.ReactNode |
||||
api: Api |
||||
} |
||||
type Context = { |
||||
api: Api |
||||
} |
||||
|
||||
// Just find-replace "AppContext" with whatever context name you like. (ie. DankContext)
|
||||
const AppContext = createContext<Context | null>(null) |
||||
|
||||
export const AppContextProvider = ({ api, children }: Props) => { |
||||
return <AppContext.Provider value={{ api }}>{children}</AppContext.Provider> |
||||
} |
||||
|
||||
export const useAppContext = () => { |
||||
const context = useContext(AppContext) |
||||
|
||||
if (!context) |
||||
throw new Error( |
||||
'AppContext must be called from within the AppContextProvider', |
||||
) |
||||
|
||||
return context |
||||
} |
@ -1,53 +0,0 @@ |
||||
import { useCallback, useEffect, useState } from 'react' |
||||
import Axios from 'axios' |
||||
import { setHeaders } from '../utils/jwt' |
||||
|
||||
type Options = { |
||||
subscribe: boolean |
||||
} |
||||
|
||||
export type Response<T> = |
||||
| { |
||||
data: T |
||||
loading: false |
||||
error: false |
||||
refetch: () => void |
||||
} |
||||
| { |
||||
data: null |
||||
loading: false |
||||
error: true |
||||
refetch: () => void |
||||
} |
||||
| { |
||||
data: null |
||||
loading: true |
||||
error: false |
||||
refetch: () => void |
||||
} |
||||
|
||||
export const useGet = <T>(path: string, options?: Options): Response<T> => { |
||||
const [data, setData] = useState<T | null>(null) |
||||
const [error, setError] = useState(false) |
||||
|
||||
const get = useCallback(async () => { |
||||
try { |
||||
const { data } = await Axios.get<T>(`/api/${path}`, { ...setHeaders() }) |
||||
setData(data) |
||||
} catch (err) { |
||||
setError(true) |
||||
} |
||||
}, [path]) |
||||
|
||||
useEffect(() => { |
||||
get() |
||||
}, [get]) |
||||
|
||||
if (data) { |
||||
return { data, loading: false, error: false, refetch: get } |
||||
} else if (error) { |
||||
return { data: null, loading: false, error: true, refetch: get } |
||||
} else { |
||||
return { data: null, loading: true, error: false, refetch: get } |
||||
} |
||||
} |
Loading…
Reference in new issue