import { useQuery, gql, useMutation } from "@apollo/client";
const Questions = () => {
const [modal, setModal] = useState(false)
const QUESTION_QUERIES = gql`
query getQuestions(
$subjectRef: ID
$gradeRef: ID
$chapterRef: ID
$status: String
) {
getQuestions(
subjectRef: $subjectRef
gradeRef: $gradeRef
chapterRef: $chapterRef
status: $status
) {
id
question_info
question_type
answer
level
published
subjectRef
gradeRef
chapterRef
levelRef
streamRef
curriculumRef
options
status
subject
grade
chapter
stream
curriculum
}
}
`;
const { loading, error, data } = useQuery(QUESTION_QUERIES);
return (
<div>
</div>
)
}
这是我的react graphql代码。如果模态状态从true变为false或从false变为false,我想在模态更改时使用state获取数据真的,它会调用api来再次获取问题
请看一下如何解决这个问题。
使用useLazyQuery
:
CCD_ 2。
然后用modal
作为依赖变量创建useEffect
,并在useEffect
中调用updateFn
您想在modal
状态更改后获取数据,所以您只需使用useEffect
并将modal
放在useEffect
的依赖列表中,对于useQuery
,还有一个名为refetch
的函数,逻辑如下
const { loading, error, data, refetch } = useQuery(QUESTION_QUERIES);
useEffect(() => {
// the reason I put if condition here is that this useEffect will
// also run after the first rendering screen so you need to put a check
// to do not run refetch in that condition
if (data) refetch();
}, [modal]);