-
I'm building hooks with zod to make a library for an api i'll be using in multiple apps. When I call the useMutation hook for login for example, typescript is assuming that data will always be present const { data, mutate } = useLoginMutation() I have const data: {
token: string;
name: string;
tokenPass: string;
} Whereas it should be const data: {
token: string;
name: string;
tokenPass: string;
} | undefined Here is my hook: const LoginInput = z
.object({ email: z.string(), password: z.string() })
.transform((data) => ({ Email: data.email, Password: data.password }))
export type TLoginInput = z.input<typeof LoginInput>
const LoginOutput = z
.object({ Token: z.string(), Name: z.string(), TokenPass: z.string() })
.transform((data) => ({ token: data.Token, name: data.Name, tokenPass: data.TokenPass }))
export type TLoginOutput = z.output<typeof LoginOutput>
const mutate = fetcher<TLoginInput, TLoginOutput>({
method: HTTPMethod.POST,
path: `/accounts/login`,
requestSchema: LoginInput,
responseSchema: LoginOutput,
})
export const useLoginMutation = (options?: UseMutationOptions<TLoginOutput, unknown, TLoginInput>) => {
return useMutation(['login'], (input: TLoginInput) => mutate(input), {
retry: false,
onSuccess: ({ token }) => {
axiosClient.defaults.headers.common['Authorization'] = `Bearer ${token}`
},
...options,
})
} Here is the fetcher export const axiosClient = axios.create({ baseURL: `https://someurl.com/api` })
export default function fetcher<Request, Response>({
method,
path,
requestSchema,
responseSchema,
}: {
method: HTTPMethod
path: string
requestSchema: z.ZodEffects<ZodTypeAny> | z.ZodType<Request>
responseSchema: z.ZodEffects<ZodTypeAny> | z.ZodType<Response>
}): (data: Request) => Promise<Response> {
return function (requestData: Request) {
async function apiCall() {
const parsedRequest = requestSchema.parse(requestData)
const response = await axiosClient({
method,
url: path,
[method === HTTPMethod.GET ? 'params' : 'data']: parsedRequest,
})
return responseSchema.parse(response.data)
}
return apiCall()
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
schulzf
May 9, 2023
Replies: 1 comment
-
forgot to enable structNullChecks |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
schulzf
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
forgot to enable structNullChecks