我有一个 NextJS 项目,它使用 NextAuth 进行会话管理,然后使用 React Query 来检索前端数据。
但是,使用当前格式(如下所示), useSession() 将undefined在检查会话是否已通过身份验证时返回,然后undefined在reactQuery中使用它,它本身将返回undefined. 如何确保仅在成功检索会话并包含 userID 之后才调用 useQuery,然后将其传递给 useQuery?
const AirdropsPage = () => {
const { data: session } = useSession();
const { isLoading, isError, data } = useQuery(["airdropsData"], () =>
fetch(`/api/airdrops?id=${session?.user?.id}`).then((res) => res.json()) //id is undefined
);
return (
{isLoading ? (
<Loader />
) : data ? (
<Table data={data.airdrops} columns={columns} />
) : null}
);
};
Run Code Online (Sandbox Code Playgroud) 在我的第一个Next.js项目中,我有一个在服务器端呈现的文章组件。我想从客户端获取文章标签,否则我会得到太多 DOM 元素。所以这就是我想出的:
const ArticlesPage = () => {
const [tags, setTags] = useState([])
const { isLoading, isError, data, error } = useQuery('tags', getTags, {
onSuccess: () => setTags(data)
}
//...
})
console.log('tags are:', tags)
return (
<>
...
{!isLoading && !isError &&
<TagsComponent tags={tags} />
}
{isLoading &&
<div> Loading tags...</div>
}
{isError &&
<div> Error fetching tags</div>
}
</>
Run Code Online (Sandbox Code Playgroud)
问题是标签异想天开地呈现在文章页面上,也就是说,当我刷新页面时,它们不会显示,但当我重新关注页面时,标签会显示。我也没有看到任何Loading或Error正在渲染。所以我很困惑这里发生了什么?
我怎样才能解决这个问题?
我正在使用 React Query 进行 API 调用,但是当我重新加载页面时,状态会丢失。我在 StackOverflow 上发布了一个问题,询问是否有一种方法可以在 React-Query 中保存数据,然后有人回答说有一种方法可以使用 persistQueryClient,但我尝试阅读文档,但我仍然不明白它是如何工作的。有人可以向我解释一下吗?
https://tanstack.com/query/v4/docs/react/plugins/persistQueryClient
我正在开发一个使用 React 查询、https ://react-query.tanstack.com/、React 钩子和功能组件的 React JS 项目。但是当我对 API 调用使用反应查询时它会抛出错误。
这是我的组件以及我如何在其中使用查询。
const App = () => {
const [ list, updateList ] = useState([])
const info = useQuery(["item-list"], getList, {
retry: false,
refetchOnWindowFocus: false,
})
if (info.status == "success") {
updateList(info.data)
}
return (
//view components here
)
}
Run Code Online (Sandbox Code Playgroud)
这是我的 getList API 调用逻辑
export const getList= async () => {
const { data } = await api.get("8143487a-3f2a-43ba-b9d4-63004c4e43ea");
return data;
}
Run Code Online (Sandbox Code Playgroud)
当我运行我的代码时,我收到以下错误:
react-dom.development.js:14815 未捕获的错误:重新渲染太多。React 限制渲染次数以防止无限循环。
我的代码有什么问题?
因此,我正在查询我的上下文 API 通过表单选择更新更新的所有内容。
所以,操作顺序就像这样。
所以,就像这样..
有值... ...查询API调用...没有值...返回查询有值
const ProductPage = (props) => {
const { question } = useContextStateWhatever();
/* Queries */
const { data = {}, isFetched } = useProductUpdatePrice({ questions });
const value = derivePriceFromResponse(data.products);
return (
<SomeComponentRendered value={value} />
)
Run Code Online (Sandbox Code Playgroud)
因此,您可以在查询中的“旧值”和请求之间看到,传递的“值”将是未定义的。然后查询返回更新后的值。
我希望查询将返回任何以前的值,但“queryKey”会随着表单的每次选择而变化。深度查询Key。
我希望我不必再将这个值从 useEffect 中放入本地状态,或者使用 useRef 并创建钩子来交回“前一个”值,直到新值准备好......这不是react-query为了,对吗?我的意思是,每当“上下文 api”发生变化时,我不应该能够进行查询调用,并且不希望出现未定义的延迟差异。有什么策略可以克服这个问题吗?
由于每个查询的“queryKey”都是不同的(主要用于正常形式的交互),我可以看到它如何在解决之前无法返回先前的值等等......有什么想法吗?
有什么想法吗?
这是我正在使用的代码。这对我来说没有任何意义,因为该错误基本上告诉我在使用查询时我没有向它传递函数,但我是。我也没有直接调用该函数。任何帮助将不胜感激
import logo from "./logo.svg";
import "./App.css";
import { useEffect, useState } from "react";
//import Posts from './components/Posts'
import axios from "axios";
import { useQuery } from "react-query";
import React from "react";
async function fetchPosts() {
const data = await fetch("http://swapi.dev/api/planetsd");
return data.json();
}
function App() {
const { data, status, error } = useQuery(
"stuffthing",
async () => await fetchPosts()
);
// first argumello\'ent is a string to cache and track the query result
if (status === "error") { …Run Code Online (Sandbox Code Playgroud) 我试图将获取的数据分配useQuery给一个状态,以根据请求是否为空来处理更好的条件渲染。
目前,我正在尝试做的事情如下所示:
...
const [userLists, setUserLists] = useState({});
...
const lists = useQuery(["lists"], api.fetchLists);
if(lists.isLoading){
//
} else {
setUserLists(lists.data.lists); // this line is causing the issue
}
Run Code Online (Sandbox Code Playgroud)
浏览器返回给我一个Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
为什么会出现这种情况呢?如何将结果实际放入 useState 挂钩中?
我试图GET使请求获取单个用户的查询无效。由于有很多用户,我必须根据我的GET请求提供 2 个查询键,fetch-user并且id:
useQuery<User, AxiosError>(['fetch-user', id], () => fetchUser(id));
Run Code Online (Sandbox Code Playgroud)
每当我作为PATCH用户时,我想要使所述请求无效,否则将显示以前的(缓存的)值而不是更新的值。
fetch-user如何使具有特定键(在我的情况下)和 的附加键的查询无效id?
挂钩GET具有特定 id 的用户:
const fetchUser = (id: number): Promise<User> => {
return axios.get(`/users/${id}`).then((resp) => resp.data);
};
export const useUserData = (id: number) => {
return useQuery<User, AxiosError>(['fetch-user', id], () => fetchUser(id));
};
Run Code Online (Sandbox Code Playgroud)
挂钩PATCH具有特定 id 的用户:
const patchUser = (id: number, body: PatchUser): Promise<User> => {
return axios
.patch(`/users/${id}`, body, …Run Code Online (Sandbox Code Playgroud) 当我添加 pageProps deHydratedState 时,出现错误Property 'deHydratedState' does not exit on type '{}' 。我试图使用 tanstack 网站https://tanstack.com/query/v4/docs/react/guides/ssr#using-Hydration中给出的文档配置 NextJs 应用程序以进行反应查询
我的应用程序是 NextJS Typescript。下面是我的配置文件
_app.tsx
// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();
// interface MyAppProps extends AppProps {
// emotionCache?: EmotionCache;
// }
type CustomPage = NextPage & {
requiresAuth?: boolean;
redirectUnauthenticatedTo?: string;
dehydratedState?: any;
};
interface CustomAppProps extends Omit<AppProps, "Component"> {
Component: CustomPage;
emotionCache?: EmotionCache;
}
type ThemeMode = "light" …Run Code Online (Sandbox Code Playgroud) react-query ×9
reactjs ×8
javascript ×4
next.js ×3
react-hooks ×3
typescript ×2
next-auth ×1
node.js ×1