I spent some time learning client-side queries using Apollo Client in React. Since I didn't have a strong understanding of Apollo and GraphQL, I had some trouble recognising and understanding how formatting worked in TypeScript for Apollo and GraphQL. Here, I intend to highlight anything I considered important details to help understand Apollo Client.
Note that this has been altered to remove private information.
The declaration to retrieve data was somewhat difficult to understand at first:
const {
data: { wantedData = [] } = {},
} = useWantedData();
It creates a constant, wantedData, from data returned by the useWantedData method. If wantedData is null or nonexistent, it will instead return an empty array. If you don't want it to always return an empty array (as in, you sometimes want to receive null), you can instead write:
const {
data: { wantedData } = {},
} = useWantedData();
If useWantedData also returned another field, such as error, then that value can be included as follows:
const {
data: { wantedData = [] } = {},
error,
} = useWantedData();
Though that requires a change to useWantedData's file, as shown in the next section.
import { useQuery } from '@apollo/client';
import { GetWantedDataQuery } from '../data/queries/wantedData';
import { WantedData } from '../types/WantedData';
export const useWantedData = () => {
// This query will return a list
// When needed, we can import this hook into component
const queryResult = useQuery<{
wantedData: WantedData[]
}>(GetWantedDataQuery);
if (queryResult?.data?.wantedData) {
return {
...queryResult,
data: {
...queryResult.data,
},
};
}
return queryResult;
};
Any use of ... in a file copies everything from the original value adjacent to it, but alters any information as specified (such as data).
The section
<{ wantedData: WantedData[] }>
“describes” the values (and their types) that are returned by useQuery (imported from Apollo Client).
To return more than one value, it would be written as follows:
<{
wantedData: WantedData[],
error: ApolloError
}>
import gql from 'graphql-tag';
export const GetWantedDataQuery = gql`query GetWantedData {
wantedData {
id
name {
firstName
lastName
}
}
}`;
This is the file containing the GraphQL query to get the wanted data. It is a useful source to copy the query into a sandbox.