在api请求准备好之前无法弄清楚如何跳过查询,因此它不会在带有useSWR的apollo useQuery中返回未定义的变量
Posted
技术标签:
【中文标题】在api请求准备好之前无法弄清楚如何跳过查询,因此它不会在带有useSWR的apollo useQuery中返回未定义的变量【英文标题】:Can't figure out how to skip query until api request is ready so it doesnt return a undefined variable in apollo useQuery with useSWR 【发布时间】:2021-06-08 21:02:22 【问题描述】:我有以下代码使用 useSWR 访问用户 api,如果我在控制台记录用户前两次呈现未定义的情况。 useQuery 抱怨 user.id
未定义,这在渲染中的某些时候是正确的,但是我尝试传递一个跳过选项,它可以为具有类似问题的 cookie 变量传递一个跳过选项,要么我不知道如何传递两个变量来跳过,或者只能取一个,或者不能一起工作。
这是我目前的代码
import Layout from "../components/Layout";
import useForm from "react-hook-form";
import useSWR from "swr";
import gql, useQuery from "@apollo/client";
import useState, useEffect from "react";
export const CATALOG_VALUES = gql`
query GetCatalogValues($id: ID!)
findUserByID(id: $id)
catalog
decor
clothing
supplies
furniture
_id
email
`;
const fetcher = (url) => fetch(url).then((r) => r.json());
export default function Welcome()
const data: user, error: userError = useSWR("/api/user");
const data: cookieData, error: cookieError = useSWR(
"/api/cookie",
fetcher
);
var cookieBearer = `Bearer $cookieData`;
const loading, error, data = useQuery(CATALOG_VALUES,
variables: id: user.id ,
context:
headers:
authorization: cookieBearer,
,
,
skip: !cookieBearer || !user, // I have tried many different things here
);
const register, handleSubmit, errors = useForm();
const onSubmit = (data) => console.log(data);
console.log(errors);
if (loading) return <p>Loading...</p>;
if (error) return <p>error.message</p>;
if (cookieError) return <p>Cookie Error</p>;
if (!user) return <p>loading</p>;
if (userError) return <div>failed to load</div>;
return (
<Layout>
<h1>Add your Catalog Type Below</h1>
user.id
<form onSubmit=handleSubmit(onSubmit)>
<h2>Decor</h2>
<input
name="Add Form"
type="radio"
value="Decor"
ref=register( required: true )
/>
<div>
<input type="submit" />
</div>
</form>
</Layout>
);
【问题讨论】:
!cookieBearer
条件没有意义:p
哦,因为它是一个带或不带cookieData的字符串,所以它不会跳过
【参考方案1】:
创建一个组件并传递道具修复它
const Form = ( cookieBearer, user ) =>
const loading, error, data = useQuery(CATALOG_VALUES,
variables: id: user.id ,
context:
headers:
authorization: cookieBearer,
,
,
);
console.log(data);
if (loading) return <p>Loading...</p>;
if (error) return <p>error.message</p>;
return <p>hello world</p>;
;
cookieBearer && user && <Form cookieBearer=cookieBearer user=user />
【讨论】:
以上是关于在api请求准备好之前无法弄清楚如何跳过查询,因此它不会在带有useSWR的apollo useQuery中返回未定义的变量的主要内容,如果未能解决你的问题,请参考以下文章
Alamofire 4 请求返回 NSArray,无法弄清楚如何在 Swift 3 中使用 SwiftyJSON 进行解析
我的网站上的 PHP 联系表单错误。 PHP 新手,但我发誓这之前有效并且停止了,我无法弄清楚如何修复它 [重复]