TanStackT
TanStack7mo ago
8 replies
popular-magenta

Using useQuery result in custom hook

Hi,
I'm having trouble using the result of a query in a custom hook, as the hook runs before the promise is resolved, resulting in passing it an undefined object.
My query looks something like this:
const {data: formResponse, isLoading} = useQuery<DynamicForm>({
    queryKey: ['form', formId],
    queryFn: async () => {
        try {
            const form = await getFormById(Number(formId));
            const parsedForm = parseForm(form.data ?? ({} as DynamicFormDto));
            return parsedForm;
        } catch (err) {
            console.error('Error in form query:', err);
            throw err;
        }
    },
    retry: false,
});

and then i just want to use it like this:
const {state, actions} = useForm(formResponse);


formResponse gets passed as undefined, which the compilers warns about, but I don't know how i can narrow it down to the supposed type, since we can't call hooks conditionally.

Any help is very much appreciated, thank you.
Was this page helpful?