state
Overview
state function is used to create a state slice.
state provides a descriptor which can be used to define one of the following:
- onInit
- mutationUpdate
- effect
- optimisticResponse
- refetchQueries
- typePolicies
- resolver
- action
- possibleTypes
Defining state
Defining a state slice is as simple as calling state function.
export const themeState = state(descriptor => ...)
A state slice file name should be in the format <stateName>.state.ts, this is a requirement as per our setup guide.
<stateName> is singular by convention for simplicity.
Adding state
Once a state slice is created it needs to be provided to ApolloOrbitProvider states array.
ApolloOrbitProvider must be nested under ApolloProvider to ensure that it has access to the ApolloClient instance used in the app.
ApolloOrbitProvider can be used multiple times and at any level in the application, including in lazy loaded components.
States register before children render, making type policies and onInit writes available immediately. Registration happens once per client, including duplicate entries, nested providers, remounts and Strict Mode. Another client initialises the state separately.
Define states outside components for stable identity. Providers register their initial states and client on mount. Mount another provider for lazy-loaded states; remount when replacing the client.
Example
import { themeState } from './states/theme.state';
root.render(
<ApolloProvider client={client}>
<ApolloOrbitProvider states={[themeState]}>
<App />
</ApolloOrbitProvider>
</ApolloProvider>,
);
onInit
onInit defines a callback that is invoked when the state is initialised.
export const themeState = state(descriptor => descriptor
.onInit(cache => cache.writeQuery(...))
);
onInit callback accepts the cache instance and can be used to initialise cache data for the state. More on this in local state guide.