[英]Make api call with useSWR when navigation params updates and store his value on custom hook with contextAPI
I want to make an API call with useSWR when navigation(route)'s params updates and store his value on a custom hook with contextAPI.我想在导航(路由)的参数更新时使用 useSWR 进行 API 调用,并将其值存储在带有 contextAPI 的自定义挂钩上。
I have this component UsersPage
that renders a list of users, it needs to have pagination, and when I click on some user, share his link based on his id and query requested (page, userId, nationality=nat, gender, etc).我有这个组件UsersPage
呈现用户列表,它需要分页,当我点击某个用户时,根据他的 ID 和请求的查询(页面、用户 ID、国籍 = nat、性别等)分享他的链接。
I'm considering using useSWR for a better User Experience.我正在考虑使用 useSWR 来获得更好的用户体验。
I tried我试过
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]);
on custom hook useUsers the function getQuery is在自定义挂钩 useUsers 上,function getQuery 是
const getQuery = () => {
const query = `&gender=${selectedGender}&nat=${nationality}&page=${page}&results=${results}`;
return query;
};
On useFetch hook I have:在 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 };
}
I received: 'React Hook "useFetch" cannot be called inside a callback.我收到:'无法在回调中调用 React Hook“useFetch”。 React Hooks must be called in a React function component or a custom React Hook function.'必须在 React function 组件或自定义 React Hook function 中调用 React Hooks。
Have someone done this before and share your experience/advice?以前有人这样做过并分享您的经验/建议吗?
I would try something like this:我会尝试这样的事情:
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.