Connect a React app to your GraphQL API with Apollo Client, queries, mutations, and caching.
npm install @apollo/client graphqlimport { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
const httpLink = createHttpLink({ uri: 'http://localhost:4000/graphql' });
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('token');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
}
};
});
export const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});import { ApolloProvider } from '@apollo/client';
import { client } from './apolloClient';
function App() {
return (
);
}import { useQuery, useMutation, gql } from '@apollo/client';
const GET_USERS = gql`
query GetUsers {
users { id name email }
}
`;
const CREATE_USER = gql`
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) { id name email }
}
`;
function UserList() {
const { loading, error, data } = useQuery(GET_USERS);
const [createUser] = useMutation(CREATE_USER, {
refetchQueries: [GET_USERS], // refetch after mutation
});
if (loading) return Loading...
;
if (error) return Error: {error.message}
;
return (
{data.users.map(u => {u.name})}
);
}ApolloProvider and makes the client available everywhere.useQuery(QUERY) returns { loading, error, data }. Handles fetching automatically.useMutation(MUTATION) returns a function to call when ready, plus state.refetchQueries in useMutation tells Apollo to re-run specific queries after the mutation completes.