'Apollo Client useQuery not getting data because of cache
I'm using Apollo client GraphQL with React Native,
I have a query that launches but data stays undefined, I get data only when I change fetch policy from network-only to cache-only, but then if I logout and login the problem persists and I get nothing.
- This is how the component works
// in MyComponent.tsx
export default function MyComponent(): JSX.Element {
const [flashCards, setFlashCards] = useState<any>([]);
const { loading, error, data, refetch } = useQuery<
{
getAllFlashcards: {
id: string;
flashcard: Array<{ id: string; title: string }>;
};
},
{ classroomId: string }
>(GET_ALL_FLASH_CARDS, {
fetchPolicy : "network-only", //<--------- 1. if i comment this
fetchPolicy: "cache-only", //<------- 2. then uncomment this then i get data
variables: {
classroomId: classroomId,
},
});
if (loading && data) {
console.log("loading and adata");
}
if (loading && !data) {
console.log("loading and no data");
}
if (error) {
console.log(error);
}
useEffect(() => {
if (data) {
setFlashCards(data.getAllFlashcards);
}
}, [data]);
return(<>...<>)
}
- I followed Apollo client docs when implementing the authentication by clearing the store when I signin and signout, but still... the problem persist
// in App.tsx
export default function App() {
const [classroomId, setClassroomId] = useState<any>("");
const [state, dispatch] = React.useReducer(
(prevState: any, action: any) => {
switch (action.type) {
case "SIGN_IN":
return {
...prevState,
isSignout: false,
userToken: action.token,
};
case "SIGN_OUT":
return {
...prevState,
isSignout: true,
userToken: null,
};
}
},
{
isLoading: true,
isSignout: false,
userToken: null,
}
);
//passed to the application using a context provider.
const auth = React.useMemo(
() => ({
signIn: async (data: any) => {
await client.resetStore();
await SecureStore.setItemAsync("userToken", data.token);
dispatch({ type: "SIGN_IN", data });
},
signOut: async() => {
await client.resetStore();
await SecureStore.deleteItemAsync("userToken")
dispatch({ type: "SIGN_OUT" })
}
}),
[]
);
Why fetched data is undefined but visible only when I change fetch policy even though I am using fetchPolicy : "network-only" ?, your help is appreciated, thank you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
