useFormik can not get initial values from response by useQuery?

25 views Asked by At

---React has detected a change in the order of Hooks called by Detail. This will lead to bugs and errors if not fixed.---


I'm getting hooks order error when I set the useForkmik initial values with useQuery responses data.

const Detail: FC<Props> = ({ requestId }) => {
    const [isSaveButtonVisible, setIsSaveButtonVisible] = useState<boolean>(false);
    const { openModal, closeModal } = useModal();
    const {
        isLoading: isButtonsLoading,
        data: buttonsResponse,
        refetch: buttonsRefetch,
    } = useQuery(
        `request-buttons-${requestId}`,
        () => {
            return getRequestActionButtons(requestId);
        },
        queryConfig
    );

    const {
        isLoading: detailIsLoading,
        data: detailResponse,
        refetch: detailRefetch,
    } = useQuery(
        `request-detail-${requestId}`,
        () => {
            return getRequestDetail(requestId);
        },
        queryConfig
    );
    const requestDetail = useMemo(() => detailResponse, [detailResponse]);
    const requestActionButtons = useMemo(() => buttonsResponse?.flowActions, [buttonsResponse]);

    if (detailIsLoading || isButtonsLoading) {
        return <RequestDetailSkeleton />;
    }
    if (!detailIsLoading && !isButtonsLoading && (!requestDetail || !requestActionButtons)) {
        return;
    }
    if(!requestDetail) return


    const requestDetailFormik = useFormik({
        initialValues: requestDetail,
        onSubmit: async (values) => {
        },
    });
    
    const handleRefetchDetailAsync = async () => {
        const updatedDetailRes = await detailRefetch();
        
        await buttonsRefetch();
        requestDetailFormik.resetForm({ values: updatedDetailRes.data });
    };


    useKeyboardControl(() => {
        if (!isSaveButtonVisible) return;
        requestDetailFormik.handleSubmit();
    }, "s");

    useAskBeforeUnload(isSaveButtonVisible);

    useEffect(() => {
        if (requestDetail && requestDetailFormik) {
            const isDifferent = checkIfDifferentOnForm(requestDetail, requestDetailFormik.values);
            setIsSaveButtonVisible(isDifferent);
        }
    }, [requestDetailFormik.values]);

When I debug the flow I saw useFormik rerender 4 times the component. On the 4. cycle it throw the exception.

I tried to give initial values to a state then pass this initial values to formik and update this initials in useEffect but I got no result.

0

There are 0 answers