fix: token async update flow
This commit is contained in:
parent
70aac95661
commit
9bfd15819e
@ -5,8 +5,8 @@ export interface AuthContextValue {
|
||||
user: User | null
|
||||
token: AuthToken
|
||||
logout: () => void
|
||||
signUp: (payload: SignUpPayload) => Promise<void>
|
||||
addBirthday: (birthday: string) => Promise<void>
|
||||
signUp: (payload: SignUpPayload) => Promise<AuthToken>
|
||||
addBirthday: (birthday: string, token: AuthToken) => Promise<void>
|
||||
}
|
||||
|
||||
export interface SignUpPayload {
|
||||
@ -19,7 +19,7 @@ const initialContext: AuthContextValue = {
|
||||
token: '',
|
||||
user: null,
|
||||
logout: () => undefined,
|
||||
signUp: () => Promise.resolve(),
|
||||
signUp: () => Promise.resolve(''),
|
||||
addBirthday: () => Promise.resolve(),
|
||||
}
|
||||
|
||||
|
||||
@ -1,13 +1,14 @@
|
||||
import { useDispatch, useSelector } from 'react-redux'
|
||||
import { AuthContext, SignUpPayload } from './AuthContext'
|
||||
import { RootState, actions } from '../store'
|
||||
import { AuthToken } from '../types'
|
||||
import routes from '../routes'
|
||||
|
||||
export function AuthProvider({ children }: React.PropsWithChildren<unknown>): JSX.Element {
|
||||
const dispatch = useDispatch()
|
||||
const token = useSelector((state: RootState) => state.token)
|
||||
const user = useSelector((state: RootState) => state.user)
|
||||
const signUp = async ({ email, timezone, locale }: SignUpPayload): Promise<void> => {
|
||||
const signUp = async ({ email, timezone, locale }: SignUpPayload): Promise<AuthToken> => {
|
||||
const response = await fetch(routes.server.token(), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@ -17,6 +18,7 @@ export function AuthProvider({ children }: React.PropsWithChildren<unknown>): JS
|
||||
const { auth: { token, user } } = await response.json()
|
||||
dispatch(actions.token.update(token))
|
||||
dispatch(actions.user.update(user))
|
||||
return token
|
||||
} else {
|
||||
const { errors } = await response.json()
|
||||
if (Array.isArray(errors)) {
|
||||
@ -28,7 +30,7 @@ export function AuthProvider({ children }: React.PropsWithChildren<unknown>): JS
|
||||
}
|
||||
}
|
||||
}
|
||||
const addBirthday = async (birthday: string): Promise<void> => {
|
||||
const addBirthday = async (birthday: string, token: AuthToken): Promise<void> => {
|
||||
const response = await fetch(routes.server.user(), {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
|
||||
@ -42,7 +42,7 @@ function EmailEnterPage(): JSX.Element {
|
||||
timezone: getClientTimezone(),
|
||||
locale: getClientLocale(),
|
||||
})
|
||||
.then(() => addBirthday(`${birthdate} ${birthtime}`))
|
||||
.then((token) => addBirthday(`${birthdate} ${birthtime}`, token))
|
||||
.then(() => navigate(routes.client.subscription()))
|
||||
.catch((error: Error) => setError(error))
|
||||
.finally(() => setIsLoading(false))
|
||||
|
||||
Loading…
Reference in New Issue
Block a user