简体   繁体   中英

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>
        )

    }

Here is my react graphql code. I wants to fetch data when modal change using state if modal status change to true to false or false to true it will make api call to fetch questions again

Please take a look how to solve the issue.

use useLazyQuery :

const [updateFn,{ loading, error, data }]= useLazyQuery(QUESTION_QUERIES); .

Then create useEffect with modal as dependency variable, and call updateFn inside useEffect

You want to fetch data after the modal state change, So you simply use useEffect and put modal in the dependency list of the useEffect and for useQuery there is also a function called refetch , the logic would be like this

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM