React Apollo Client, loading only change to true on first time query
I have a simple structure of files on a same directory (./src/
)
App.js
import React from "react";
import {
ApolloClient,
ApolloProvider,
createHttpLink,
InMemoryCache,
} from "@apollo/client";
import Gql from "./Gql";
const App = () => {
const client = new ApolloClient({
link: createHttpLink({
uri: "https://api.spacex.land/graphql/",
}),
cache: new InMemoryCache(),
});
return (
<ApolloProvider client={client}>
<Gql />
</ApolloProvider>
);
};
export default App;
Gql.js
import React from "react";
import { gql, useLazyQuery } from "@apollo/client";
const Gql = () => {
const [getQuery, { loading, data, error }] = useLazyQuery(gql`
query {
launchesPast(limit: 10) {
mission_name
launch_date_local
launch_site {
site_name_long
}
}
}
`);
if (error) {
return <div> Error . . .</div>;
}
return (
<React.Fragment>
<button
style={{ padding: "20px" }}
onClick={() => {
getQuery();
}}>
Request Query
</button>
<div>Loading: {loading ? "true" : "false"}</div>
<div>data: {JSON.stringify(data)}</div>
</React.Fragment>
);
};
export default Gql;
The loading
variable changed to true and to false on first request. But if I try to query it again and again without reloading the page. The loading
variable stay the same while the browser have a valid XHR Request to the graphql server.
Solution 1:
This is by design, the useLazyQuery
hook will only run when the params change as this will then prevent useless re-renders.