Reputation: 39
I am having strange situation with React routing with GraphQL. I have a users in /users
url and when i go to users page for the first time useQuery
is working, request is going to the server and bringing me some data. Then, if i go to another page and come back to the users page, useQuery
is not working and request is not going to the server. useQuery
is working and request is going to the server when i reload the page. Here is my code and query for Users component:
Users.js
import React, { useState, useEffect } from "react";
import { useLazyQuery, useQuery } from '@apollo/client'
import { USERS} from './queries'
const [usersList, setUsersList] = useState([])
const { loading, error, data } = useQuery(USERS);
const Users= () => {
useEffect(() => {
const result = data?.users?.payload.filter(item => item.status === "waiting" && !item.isDeleted)
setUsersList(result)
}, [loading, data])
return (
<div>
{usersList?.map(user => (
<div key={user.key}>
<h1>{user.name}</h1>
<p>{user.status}</p>
</div>
))}
</div>
)
}
queries.js
import { gql } from '@apollo/client';
export const USERS= gql`
query{
users(size: 50){
payload{
key,
isDeleted,
status,
name,
...
}
}
}`
So, final question, why useQuery is working only one time when site is reloaded, not rerendered?
Upvotes: 0
Views: 2453
Reputation: 284
This is by design –– your query's results would have been stored in Apollo Client's cache the first time that query triggered. If the query's variables haven't changed, then the query won't actually travel the network again, Apollo Client will pull the data out of its cache instead.
You could change the fetchPolicy
on your useQuery
hook if you want the request to go over the network to your server every time your hook is run: https://www.apollographql.com/docs/react/data/queries/#supported-fetch-policies
Upvotes: 1
Reputation: 138
You can use useLazyQuery and useEffect for that useLazyQuery
const [runQuery, { data, loading, called }] = useLazyQuery(yourQuery);
useEffect(() => { runQuery(); }, [location]);
I think you will get the idea ;)
EDIT: also you can change FetchPolicy on the normal to network-only query (I think this should work too): params of useQuery
Upvotes: 0