Search code examples
reactjsreact-nativereact-apolloreact-apollo-hooks

Call another query onComplete of one query in apollo client using react native


I am getting invalid hook call for nested queriesenter image description here

const fetchNotifications = useNotificationsQuery({
        variables: {
            skip: SKIP,
            take: TAKE,
        },
        async onCompleted(data){
            let ids:Array<string>=[]
            data?.notifications?.forEach((e)=>{
                ids.push(e?.id+"")
            })
            setIds(ids)
            readNotifications()
        }
    });

    const readNotifications =()=> usereadNotifications({
        variables: { notificationIds: ids},
            async onCompleted(data){
                console.log("res"+data)
            }
    })

and usereadNotifications comes from

export const readNotifications = gql` mutation readNotifications($notificationIds: [String]!) {
       readNotifications(notificationIds: $notificationIds) 
} `; 
export const usereadNotifications = (options?: QueryHookOptions) => ( 
     useMutation(readNotifications, options) 
); 

Solution

  • Since usereadNotifications uses a hook useMutation, you can't wrap it into a function and try to execute it conditionally as it breaks the rules of hooks

    However useMutation returns you a function which allows you to call the function to trigger mutation

    So use it like

    const fetchNotifications = useNotificationsQuery({
        variables: {
            skip: SKIP,
            take: TAKE,
        },
        async onCompleted(data){
            let ids:Array<string>=[]
            data?.notifications?.forEach((e)=>{
                ids.push(e?.id+"")
            })
            setIds(ids)
            readNotifications()
        }
    });
    
    const [readNotifications] = usereadNotifications({
        variables: { notificationIds: ids},
            async onCompleted(data){
                console.log("res"+data)
            }
    })