reactjs - 每次点击页面时 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));
}
解决方案
推荐阅读
- git - Git 命令 - 查找创建新分支的标签
- ruby-on-rails - 某些用户的 Redmine LDAP 身份验证失败
- rust - 如何区分 macro_rules 宏中不同种类的项目?
- android - 华为 AppGallery 上是否有任何指定的 url 格式,以便我可以在不同平台上访问和分发链接
- django - 如何限制 postgres 中的 varchar 只允许 DB 中的特定字符?
- rubygems - 无法安装邮件捕手
- xamarin - 我的应用会因为基于 WebView 而在 Play Store 或 App Store 上被拒绝吗?
- spring - Spring Security 在不使用标头的情况下获取客户端 IP
- bash - 如何使用 convert imagemagick 将 bash 脚本的输出保存到图像文件
- postgresql - 精确匹配 rtrim 函数中的 trimming_text