1
Fork 0
mirror of https://github.com/Steffo99/sophon.git synced 2024-12-22 06:44:21 +00:00

Add username validator

This commit is contained in:
Steffo 2021-09-19 16:01:08 +02:00
parent 4d6779631a
commit 53d5d6d47b
2 changed files with 31 additions and 5 deletions

View file

@ -1,7 +1,7 @@
import * as React from "react"
import {navigate} from "@reach/router";
import {Box, Form, Heading, Idiomatic as I, Panel, useFormState} from "@steffo/bluelib-react"
import {useLogin} from "./LoginContext";
import {useLogin, useUsernameFormState} from "./LoginContext";
import {useInstance} from "./InstanceContext";
import {AxiosError} from "axios-lab";
@ -20,10 +20,7 @@ export function LoginBox(): JSX.Element {
/**
* The FormState of the username field.
*/
const username = useFormState<string>("", value => {
if(value === "") return undefined
return true
})
const username = useUsernameFormState()
/**
* The FormState of the password field.

View file

@ -2,6 +2,8 @@ import * as React from "react"
import Axios, {AxiosRequestConfig, AxiosResponse} from "axios-lab";
import {useInstance, useInstanceAxios} from "./InstanceContext";
import {useNotNullContext} from "../hooks/useNotNullContext";
import {Validity} from "@steffo/bluelib-react/dist/types";
import {useFormState} from "@steffo/bluelib-react";
export interface UserData {
@ -106,3 +108,30 @@ export function useLoginAxios(config: AxiosRequestConfig) {
[instance, authHeader, config]
)
}
export function useUsernameFormState() {
const api = useInstanceAxios()
const usernameValidator = React.useCallback(
async (value: string, abort: AbortSignal): Promise<Validity> => {
if(value === "") return undefined
await new Promise(r => setTimeout(r, 250))
if(abort.aborted) return null
try {
await api.get(`/api/core/users/${value}/`, {signal: abort})
} catch(_) {
return false
}
return true
},
[api]
)
return useFormState<string>("", usernameValidator)
}