[英]How to refresh graphql data on state change
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>
)
}
這是我的反應 graphql 代碼。 我想在使用 state 進行模態更改時獲取數據,如果模態狀態更改為 true 到 false 或 false 到 true,它將使 api 再次調用以獲取問題
請看看如何解決這個問題。
使用useLazyQuery
:
const [updateFn,{ loading, error, data }]= useLazyQuery(QUESTION_QUERIES);
.
然后創建使用modal
作為依賴變量的useEffect
,並在useEffect
中調用updateFn
您想在modal
state 更改后獲取數據,因此您只需使用useEffect
並將modal
放入 useEffect 的依賴項列表中,對於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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.