[英]How can i use the useSWR hook when my response need to do some logical operations before next dependant API call
[英]Make api call with useSWR when navigation params updates and store his value on custom hook with contextAPI
我想在导航(路由)的参数更新时使用 useSWR 进行 API 调用,并将其值存储在带有 contextAPI 的自定义挂钩上。
我有这个组件UsersPage
呈现用户列表,它需要分页,当我点击某个用户时,根据他的 ID 和请求的查询(页面、用户 ID、国籍 = nat、性别等)分享他的链接。
我正在考虑使用 useSWR 来获得更好的用户体验。
我试过
import { useUsers } from "../../hooks/useUsers";
import { useFetch } from "../../hooks/useFetch";
.
.
.
const { pageNumber, userId } = useParams();
const {
selectedGender,
nationality,
results,
showDetails,
page,
isAscending,
toggleIsAscending,
selectedUser,
formattedName,
formattedBirth,
getQuery,
} = useUsers();
useEffect(() => {
const users = useFetch(getQuery());
//then update users state on useUsers Context's hook and render data on Context's child nodes
}, [pageNumber]);
在自定义挂钩 useUsers 上,function getQuery 是
const getQuery = () => {
const query = `&gender=${selectedGender}&nat=${nationality}&page=${page}&results=${results}`;
return query;
};
在 useFetch 挂钩上,我有:
import useSWR from "swr";
export function useFetch(query) {
const API_URL = process.env.REACT_APP_API_URL;
const fetcher = async (query) => {
const FormedURL = `${API_URL}${query}`;
const response = await fetch(FormedURL);
const data = await response.json();
return data.results;
};
const { data, error } = useSWR(query, fetcher);
return { users: data, error };
}
我收到:'无法在回调中调用 React Hook“useFetch”。 必须在 React function 组件或自定义 React Hook function 中调用 React Hooks。
以前有人这样做过并分享您的经验/建议吗?
我会尝试这样的事情:
const { pageNumber, userId } = useParams();
const {
selectedGender,
nationality,
results,
showDetails,
page,
isAscending,
toggleIsAscending,
selectedUser,
formattedName,
formattedBirth,
getQuery,
} = useUsers();
const { get, response } = useFetch(getQuery())
const fetchUsers = async () {
const users = await get()
if (response.ok){
// sets users...
}
}
useEffect(() => {
fetchUsers()
}, [pageNumber]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.