Primitive that generates a client and reactive GraphQL queries
| Stage | Category | Version | Last Updated | Demo |
|---|---|---|---|---|
| 3 | Network | 3.0.0-next.1 (next) | Nov 15, 2026 | Demo → |
npm i @solid-primitives/graphql@nextCreates a reactive GraphQL query client.
How to use it
Import
import { createGraphQLClient, createGraphQLMutation, gql, request,} from "@solid-primitives/graphql";// gql is a helper for creating GraphQL query strings// request is an additional function to perform GraphQL requests imperativelyUsing the client
createGraphQLClient takes 2 arguments:
url- target api endpoint, as string or accessoroptions- optional, options for thefetchfunction,headers, thefetchermethod etc. (object or accessor)fetcher- A fetch function to replace the default one, that is Fetch API on browser andnode-fetchon server.headers- A headers object to be passed to thefetchfunction.
It returns a query function. Calling it returns an async accessor: an async createMemo that runs the request, so it works with <Loading> and <Errored> like any other Solid 2.0 async source.
- Loading - the initial request suspends the nearest
<Loading>. While new variables load, the previous result stays on screen; useisPending(() => data())for a "refreshing" indicator. Render that indicator inside the<Loading>boundary: reading a pending query outside any boundary defers the whole root mount (ASYNC_OUTSIDE_LOADING_BOUNDARY). - Errors - a failed request (or a GraphQL
errorsresponse, thrown asGraphQLError) is thrown when the accessor is read, so catch it with<Errored>. - Aborting - the request receives an
AbortSignalthat is aborted when the url, options or variables change, or when the owner is disposed. Asignalpassed inoptionsis combined with it, so aborting either one cancels the request.
Refetching
Call refresh on the returned accessor to run the same request again. A bare refresh is a quiet re-ask: the new result swaps in without isPending turning true. To show a "refetching" state, use a mutation (which marks the queries it changes as pending) or wrap affects(data); refresh(data); in your own action.
import { refresh } from "solid-js";
const data = newQuery(gql`...`, { foo: "bar" });const onClick = () => refresh(data);Query options
The query function takes a third argument that is passed on to the underlying createMemo:
name- debug name shown in diagnosticsloadingValue- a value shown until the first response lands. Nothing suspends andisPendingstaysfalse, so drive first-load UI from the value itself (anullplaceholder, askeleton: truefield...). This replaces theinitialValueof Solid 1.x resources.ssrSource/deferStream- control server rendering and hydration, see the Solid 2.0 SSR docsequals- custom equality of consecutive responses
const countries = newQuery<{ countries: { name: string }[] }>( gql` query { countries { name } } `, {}, // no variables (omitting the argument works too, but `undefined` would skip the request) { name: "countries", loadingValue: { countries: [] } },);countries(); // T: { countries: { name: string }[] }Preventing immediate requests
Pass false, null or undefined as the variables (or an accessor returning one) to skip the request. The accessor returns undefined until the variables are provided.
const newQuery = createGraphQLClient("https://foobar.com/v1/api");const [queryVars, setQueryVars] = createSignal<false | object>(false);const data = newQuery(gql`...`, queryVars);
setQueryVars({ foo: "bar" }); // will fetch for the first timerefresh(data); // will refetch the second timeProviding Response Type
// query function accepts type generic for the response:const countries = newQuery<{ countries: { name: string }[] }>(gql` query { countries { name code } }`);countries(); // T: { countries: { name: string }[] } | undefinedReactive query variables
Variables passed to the query can be reactive. If they change, the query is refetched.
const [code, setCode] = createSignal("BR");const data = query( gql` query data($code: ID!) { country(code: $code) { name } } `, // function returning an object () => ({ code: code(), }),);Mutations
createGraphQLMutation takes the same url and options as createGraphQLClient and returns a mutate function. It is built on Solid 2.0's action: every call is one transaction, so optimistic writes, the request and the follow-up refresh settle together.
- Call it from event handlers.
mutateis anaction, so calling it from a component body or computation throwsACTION_CALLED_IN_OWNED_SCOPE. optimisticruns first, synchronously, with the variables. Write tocreateOptimistic/createOptimisticStoresetters there: they revert automatically if the request fails.refreshlists the queries the mutation changes. They read as pending (isPending) while the request is in flight, and are refreshed once it succeeds. If it fails they are left alone.- Errors - a failed mutation rejects the returned promise with a
GraphQLErrorand reverts the optimistic writes. multipart: truesends the request asmultipart/form-data, see file upload support.
File upload support
If the server supports the GraphQL multipart request specification it is possible to upload a File or a binary Blob of data by calling the multipartRequest function with the File/Blob instances in the variables variables.
This is especially useful for GraphQL mutations, because allows for binary uploads without the necessity to first encode the data to some text-based format like base64.
import { request, gql } from "@solid-primitives/graphql";
const result = multipartRequest( "https://foobar.com/v1/api", gql` mutation UploadImage($file: Upload!, $caption: String!) { uploadImage(file: $file, caption: $caption) { id } } `, { variables: { caption: "A nice image", file: inputElement.files[0] }, },);Migrating from Solid 1.x
- Mutations: instead of calling
requestby hand and refetching manually, usecreateGraphQLMutation. query(...)no longer returns acreateResourcetuple. Use the returned accessor directly:const [data, { refetch }] = query(...)becomesconst data = query(...)andrefresh(data).- The
resourceOptionsargument is replaced by query options:initialValuebecomesloadingValueandssrLoadFrombecomesssrSource. data.loadinganddata.errorare replaced by<Loading>,isPendingand<Errored>.- The
GraphQLResourceSourcetype is removed.
fetch on the server
When running on environments without Browser fetch, you should provide a fetcher to the options object, or add it to the global window object.
import nodeFetch from "node-fetch";import { createGraphQLClient, gql } from "@solid-primitives/graphql";
const newQuery = createGraphQLClient("https://foobar.com/v1/api", { fetcher: nodeFetch });Changelog
See CHANGELOG.md