json
Edit this pageThe json function returns a Response object that contains the provided data.
It is intended for sending JSON data from a query or action while also allowing configuration of query revalidation.
This works both in client and server (e.g., using a server function) environments.
Import
import { json } from "@solidjs/router";Type
function json<T>( data: T, init: { revalidate?: string | string[]; headers?: HeadersInit; status?: number; statusText?: string; } = {}): CustomResponse<T>;Parameters
data
- Type:
T - Required: Yes
The data to be serialized as JSON in the response body.
It must be a value that can be serialized with JSON.stringify.
init
- Type:
{ revalidate?: string | string[]; headers?: HeadersInit; status?: number; statusText?: string; } - Required: No
An optional configuration object with the following properties:
revalidate
- Type:
string | string[] - Required: No
A query key or an array of query keys to revalidate.
Passing an empty array ([]) disables query revalidation entirely.
headers
- Type:
HeadersInit - Required: No
An object containing any headers to be sent with the response.
status
- Type:
number - Required: No
The HTTP status code of the response.
Defaults to 200 OK.
statusText
- Type:
string - Required: No
The status text associated with the status code.
Examples
Invalidating Data After a Mutation
import { For } from "solid-js";import { query, action, json, createAsync } from "@solidjs/router";
const getCurrentUserQuery = query(async () => { return await fetch("/api/me").then((response) => response.json());}, "currentUser");
const getPostsQuery = query(async () => { return await fetch("/api/posts").then((response) => response.json());}, "posts");
const createPostAction = action(async (formData: FormData) => { const title = formData.get("title")?.toString(); const newPost = await fetch("/api/posts", { method: "POST", body: JSON.stringify({ title }), }).then((response) => response.json());
// Only revalidate the "posts" query. return json(newPost, { revalidate: "posts" });}, "createPost");
function Posts() { const currentUser = createAsync(() => getCurrentUserQuery()); const posts = createAsync(() => getPostsQuery());
return ( <div> <p>Welcome back {currentUser()?.name}</p> <ul> <For each={posts()}>{(post) => <li>{post.title}</li>}</For> </ul> <form action={createPostAction} method="post"> <input name="title" /> <button>Create Post</button> </form> </div> );}