首页 > 解决方案 > 每次点击页面时 React Typescript Mutation 调用 api

问题描述

我有一个简单的页面,它调用 api 来获取一些数据并将其显示在表格中。我使用一个使用突变的函数来调用 api 并返回数据和获取数据的状态。我使用以下(伪)代码来实现这一点:

    export const Instances = (props: InstanceProps) => {
    const history =
        useHistory<{
            formId: number;
            rowData: any;
            formInstanceID: number;
        }>();
    const { isLoading, isError, isSuccess, data, error } = useGetFromApi('api/list', [
        `${history.location.state.formId}`,
    ]);

if (isLoading) {
        return (
            <div>
                Page Loading
            </div>
        );
    }

    if (isError) {
        return (
            <div>
                An error occurred
            </div>
        );
    }

    if (isSuccess) {
        if (data) {
            // Map data to an array for the table component
        }
    }

    return (
        <div>
            Display table showing data
        </div>
    );
};

页面调用api成功,并在表格中显示数据。我遇到的问题是,当我单击页面上的任意位置或单击页面上存在的两个按钮时,再次调用突变并且页面在再次获取数据时冻结。它不记得它已成功加载。每次与页面交互时,如何阻止它调用 api?

变异函数的代码:

import { usePidgetIdentity } from '@workspace/utils-react';
import { useQuery } from 'react-query';
import config from '../shared/config';

export type ApiData = {
    data: any[];
};

async function callToApi(url: string, getAccessToken: () => Promise<string>) {
    const token = await getAccessToken();

    console.log('Starting api fetch');

    const response = await fetch(url, {
        method: 'GET',
        headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
    });

    console.log('Data has returned');

    if (!response.ok) {
        throw Error('An unexpected error occurred');
    }

    const apidata = await response.json();
    return { data: apidata };
}

export function useGetFromApi(url: string, parameters: string[]) {
    const { getAccessToken } = usePidgetIdentity();
    let apiUrl: string = config.FORMS_API_URL + '/' + url;

    parameters.map((parameter) => {
        apiUrl += '/' + parameter.trim();
    });

    console.log('Calling ' + apiUrl);

    return useQuery<ApiData, Error>(apiUrl, () => callToApi(apiUrl, getAccessToken));
}

标签: reactjstypescriptmutation

解决方案


推荐阅读