Skip to main content

Apollo Client

Same pattern as TanStack Query, for GraphQL with Apollo.

npm install @sinuxjs/apollo @apollo/client graphql

GraphQL Query Signal

import { createStore } from '@sinuxjs/core';
import { graphqlQuery, graphqlMutation, apolloClient } from '@sinuxjs/apollo';
import { gql } from '@apollo/client';

const GET_USERS = gql`query { users { id name } }`;

const store = createStore(
{ users: [], loading: false },
{
loadUsers: graphqlQuery({
query: GET_USERS,
mapToState: (data) => ({ users: data.users, loading: false }),
onFetch: () => ({ loading: true }),
}),
},
[apolloClient({ client: apolloInstance })]
);

GraphQL Mutation with Optimistic Updates

const CREATE_USER = gql`
mutation CreateUser($input: UserInput!) {
createUser(input: $input) { id name }
}
`;

const store = createStore(
{ users: [] },
{
createUser: graphqlMutation({
mutation: CREATE_USER,
variables: (input) => ({ input }),
optimistic: (state, input) => ({
users: [...state.users, { ...input, id: 'temp' }]
}),
mapToState: (data, state) => ({
users: state.users.map(u => u.id === 'temp' ? data.createUser : u)
}),
refetchQueries: [GET_USERS],
}),
},
[apolloClient({ client: apolloInstance })]
);

API Reference

ExportDescription
graphqlQuery(opts)Signal factory for GraphQL queries
graphqlMutation(opts)Signal factory for GraphQL mutations
apolloClient({ client })Middleware