You could use a combination of local state (useState) and useLazyQuery.
From what I understand you have multiple components (or screens, tabs, whatever) mounted at the same time, say ScreenA and ScreenB. In each of them you query GET_USERS, but when your query results update in ScreenB, you don't want to also update the results in ScreenA.
With useLazyQuery this could look like this:
- Create a custom hook for easy reusability across components
export const useLazyGetUsers = () => {
const [users, setUsers] = useState()
const [queryGetUsers] = useLazyQuery(GET_USERS, {
onCompleted: (data) => setUsers(data.users),
onError: (error) => console.log('onError', { error }), // handle errors as you wish
fetchPolicy: "cache-and-network", // or whatever you want
})
return {queryGetUsers, users}
}
- In ScreenA, use the hook and fetch the query:
const ScreenA = () => {
const {queryGetUsers, users} = useLazyGetUsers()
return (
<TouchableOpacity onPress={() => queryGetUsers()}>
<Text>Get users</Text>
</TouchableOpacity>
)
}
- In ScreenB, also use the hook.
Note that you can call queryGetUsers
whenever you want, on mount, on TouchableOpacity press, or whenever.
const ScreenB = () => {
const {queryGetUsers, users} = useLazyGetUsers()
useEffect(() => {
queryGetUsers()
}, [])
return (
...
)
}
- Use
users
as you wish. If you call queryGetUsers
in ScreenA, it will not update the value of users
in ScreenB.
This is not a 100% Apollo solution but it makes minimal use of local state and the hooks makes it very easy to reuse. I hope this solves your issue!
You can read more about useLazyQuery
here:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…