}>
@@ -84,5 +83,5 @@ import { Switch, Match } from "solid-js"
Outcome 2
-
+;
```
diff --git a/src/routes/concepts/control-flow/data.json b/src/routes/concepts/control-flow/data.json
index 3b874c4f05..e8261711d7 100644
--- a/src/routes/concepts/control-flow/data.json
+++ b/src/routes/concepts/control-flow/data.json
@@ -2,9 +2,9 @@
"title": "Control flow",
"pages": [
"conditional-rendering.mdx",
- "dynamic.mdx",
- "list-rendering.mdx",
- "portal.mdx",
- "error-boundary.mdx"
+ "dynamic.mdx",
+ "list-rendering.mdx",
+ "portal.mdx",
+ "error-boundary.mdx"
]
}
diff --git a/src/routes/concepts/control-flow/dynamic.mdx b/src/routes/concepts/control-flow/dynamic.mdx
index 671eda05b1..e3f50281aa 100644
--- a/src/routes/concepts/control-flow/dynamic.mdx
+++ b/src/routes/concepts/control-flow/dynamic.mdx
@@ -7,21 +7,21 @@ order: 2
By passing either a string representing a [native HTML element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element) or a component function to the `component` prop, you can render the chosen component with the remaining props you provide.
```jsx
-import { createSignal, For } from "solid-js"
-import { Dynamic } from "solid-js/web"
+import { createSignal, For } from "solid-js";
+import { Dynamic } from "solid-js/web";
-const RedDiv = () =>
Red
-const GreenDiv = () =>
Green
-const BlueDiv = () =>
Blue
+const RedDiv = () =>
Red
;
+const GreenDiv = () =>
Green
;
+const BlueDiv = () =>
Blue
;
const options = {
red: RedDiv,
green: GreenDiv,
blue: BlueDiv,
-}
+};
function App() {
- const [selected, setSelected] = createSignal("red")
+ const [selected, setSelected] = createSignal("red");
return (
<>
@@ -30,12 +30,12 @@ function App() {
onInput={(e) => setSelected(e.currentTarget.value)}
>
- {(color) => }
+ {(color) => }
>
- )
+ );
}
```
@@ -46,20 +46,20 @@ Once a color is selected, the `` component will render the chosen color
For example, the following code renders the same result as the previous example:
```jsx
-import { createSignal, Switch, Match, For } from "solid-js"
+import { createSignal, Switch, Match, For } from "solid-js";
-const RedDiv = () =>
Red
-const GreenDiv = () =>
Green
-const BlueDiv = () =>
Blue
+const RedDiv = () =>
Red
;
+const GreenDiv = () =>
Green
;
+const BlueDiv = () =>
Blue
;
const options = {
red: RedDiv,
green: GreenDiv,
blue: BlueDiv,
-}
+};
function App() {
- const [selected, setSelected] = createSignal("red")
+ const [selected, setSelected] = createSignal("red");
return (
<>
@@ -68,7 +68,7 @@ function App() {
onInput={(e) => setSelected(e.currentTarget.value)}
>
- {(color) => }
+ {(color) => }
}>
@@ -80,7 +80,7 @@ function App() {
>
- )
+ );
}
```
@@ -92,11 +92,9 @@ When working with these components, you can pass [props](/concepts/components/pr
This makes them available to the component you are rendering, similar to how you would pass props to components in JSX.
```jsx
-import { Dynamic } from "solid-js/web"
+import { Dynamic } from "solid-js/web";
function App() {
- return (
-
- )
+ return ;
}
```
diff --git a/src/routes/concepts/control-flow/list-rendering.mdx b/src/routes/concepts/control-flow/list-rendering.mdx
index 3227d985b8..fc0986f636 100644
--- a/src/routes/concepts/control-flow/list-rendering.mdx
+++ b/src/routes/concepts/control-flow/list-rendering.mdx
@@ -30,18 +30,19 @@ Between the `` tags, the component requires a [callback function](https://d
This structure resembles the callback used within JavaScript's [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) method, providing a familiar pattern to follow.
The function receives two arguments:
+
- `item`: represents the current item in the data collection that is being rendered over.
- `index`: the current item's index within the collection.
You can access the current `item` and `index` to dynamically set attributes or content of the JSX elements.
-Index is a [*signal*](/concepts/signals) and must be called as a function to retrieve its value.
+Index is a [_signal_](/concepts/signals) and must be called as a function to retrieve its value.
```jsx
{(item, index) => (
{item.name}
@@ -72,7 +73,7 @@ This is because `` is more concerned with the **index** of the elements i
Because of this, the `item` is a signal, allowing the _content_ at each index to change without a re-render while the index remains fixed.
```jsx
-import { Index } from "solid-js"
+import { Index } from "solid-js";
{(item, index) => (
@@ -80,12 +81,12 @@ import { Index } from "solid-js"
{item().name} - {item().completed}
)}
-
+;
```
## `` vs ``
-`` is designed to be used when the *order* and *length* of the list may change frequently.
+`` is designed to be used when the _order_ and _length_ of the list may change frequently.
When the list value changes in ``, the entire list is re-rendered.
However, if the array undergoes a change, such as an element shifting position, `` will manage this by simply **moving** the corresponding DOM node and **updating** the index.
@@ -99,14 +100,14 @@ For example, when creating a list of static elements, such as a list of links, `
This is because it will only modify the indexes of the elements in the list, rather than re-rendering the entire list.
```jsx
-import { createSignal, For } from "solid-js"
+import { createSignal, For } from "solid-js";
function StringList() {
- const [items, setItems] = createSignal(["Item 1", "Item 2", "Item 3"])
+ const [items, setItems] = createSignal(["Item 1", "Item 2", "Item 3"]);
return (
- {
// add the new item to the list
@@ -114,13 +115,13 @@ function StringList() {
/>
{(item, index) => (
-
+
{item} - {index()}
)}
- )
+ );
}
```
@@ -129,11 +130,11 @@ If you were using ``, the entire list would be re-rendered when a value cha
``, instead, will update the content at the specified index, while the rest of the list remains unchanged.
```jsx
-import { createSignal, Index } from "solid-js"
+import { createSignal, Index } from "solid-js";
function FormList() {
- const [inputs, setInputs] = createSignal(['input1','input2','input3'])
- return(
+ const [inputs, setInputs] = createSignal(["input1", "input2", "input3"]);
+ return (
- )
+ );
}
-```
\ No newline at end of file
+```
diff --git a/src/routes/concepts/control-flow/portal.mdx b/src/routes/concepts/control-flow/portal.mdx
index fe20f754fc..95ec28e8f1 100644
--- a/src/routes/concepts/control-flow/portal.mdx
+++ b/src/routes/concepts/control-flow/portal.mdx
@@ -7,11 +7,11 @@ When an element requires rendering outside of the usual document flow, challenge
`` helps with this by putting elements in a different place in the document, bringing an element into the document flow so they can render as expected.
```jsx
-import { Portal } from "solid-js/web"
+import { Portal } from "solid-js/web";
...
-
+;
```
The content nested within `` is rendered and positioned by default at the end of the document body.
@@ -25,39 +25,38 @@ This can be changed by passing a `mount` prop to ``.
The `mount` prop accepts a [DOM node](https://developer.mozilla.org/en-US/docs/Web/API/Node), which will be used as the mount point for the portal content.
```jsx
-import { Portal } from "solid-js/web"
+import { Portal } from "solid-js/web";
...
-
+;
```
-
Using `` can be particularly useful in cases where elements, like information popups, might be clipped or obscured due to the overflow settings of their parent elements.
By putting the element outside of the parent element, it is no longer bound by the overflow settings of its parent.
This creates a more accessible experience for users, as the content is no longer obscured.
-
:::info
- `` will render wrapped unless specifically targeting `document.head`.
+`` will render wrapped unless specifically targeting `document.head`.
- This is so events propagate through the Portal according to the component hierarchy instead of the elements hierarchy.
+This is so events propagate through the Portal according to the component hierarchy instead of the elements hierarchy.
By default, children will wrap in a `
`. If you portal into an SVG, then the `isSVG` prop must be used to avoid wrapping the children in a `
` and wrap in a `` instead.
```jsx
-import { Portal } from "solid-js/web"
+import { Portal } from "solid-js/web";
function Rect() {
- return (
-
-
-
- );
+ return (
+
+
+
+ );
}
function SVG() {
- return ;
+ return ;
}
```
+
:::
diff --git a/src/routes/concepts/derived-values/derived-signals.mdx b/src/routes/concepts/derived-values/derived-signals.mdx
index e0086fb456..3a3cbf0264 100644
--- a/src/routes/concepts/derived-values/derived-signals.mdx
+++ b/src/routes/concepts/derived-values/derived-signals.mdx
@@ -19,11 +19,11 @@ Similarly you can create a derived signal that relies on a store value because s
To learn more about how stores work, [you can visit the stores section](/concepts/stores).
```js
-const fullName = () => store.firstName + ' ' + store.lastName;
+const fullName = () => store.firstName + " " + store.lastName;
```
-These dependent functions gain reactivity from the signal they access, ensuring that changes in the underlying data propagate throughout your application.
-It is important to note that these functions do not store a value themselves; instead, they can update any effects or components that depend on them.
+These dependent functions gain reactivity from the signal they access, ensuring that changes in the underlying data propagate throughout your application.
+It is important to note that these functions do not store a value themselves; instead, they can update any effects or components that depend on them.
If included within a component's body, these derived signals will trigger an update when necessary.
While you can create derived values in this manner, Solid created the [`createMemo`](/reference/basic-reactivity/create-memo) primitive.
diff --git a/src/routes/concepts/derived-values/memos.mdx b/src/routes/concepts/derived-values/memos.mdx
index 1c80f75ea7..da14c571c4 100644
--- a/src/routes/concepts/derived-values/memos.mdx
+++ b/src/routes/concepts/derived-values/memos.mdx
@@ -18,16 +18,16 @@ Within this function, you can define the derived value or computations you wish
When called, `createMemo` will return a **getter** function that reads the current value of the memo:
```jsx
-import { createMemo, createSignal } from "solid-js"
+import { createMemo, createSignal } from "solid-js";
-const [count, setCount] = createSignal(0)
+const [count, setCount] = createSignal(0);
-const isEven = createMemo(() => count() % 2 === 0)
+const isEven = createMemo(() => count() % 2 === 0);
-console.log(isEven()) // true
+console.log(isEven()); // true
-setCount(3)
-console.log(isEven()) // false
+setCount(3);
+console.log(isEven()); // false
```
While memos look similar to effects, they are different in that they _return a value_.
@@ -68,10 +68,10 @@ They, however, serve different purposes and each has their own unique behaviors.
When working with memos, it is recommended that you leave them "pure".
```jsx
-import { createSignal, createMemo } from "solid-js"
+import { createSignal, createMemo } from "solid-js";
-const [count, setCount] = createSignal(0)
-const isEven = createMemo(() => count() % 2 === 0) // example of a pure function
+const [count, setCount] = createSignal(0);
+const isEven = createMemo(() => count() % 2 === 0); // example of a pure function
```
A pure function is one that does not cause any side effects.
@@ -81,17 +81,17 @@ When you introduce side effects into a memo, it can complicate the reactivity ch
This can lead to unexpected behavior, such as infinite loops, that lead your application to crash.
```jsx
-import { createSignal, createMemo } from "solid-js"
+import { createSignal, createMemo } from "solid-js";
-const [count, setCount] = createSignal(0)
-const [message, setMessage] = createSignal("")
+const [count, setCount] = createSignal(0);
+const [message, setMessage] = createSignal("");
const badMemo = createMemo(() => {
if (count() > 10) {
- setMessage("Count is too high!") // side effect
+ setMessage("Count is too high!"); // side effect
}
- return count() % 2 === 0
-})
+ return count() % 2 === 0;
+});
```
These infinite loops can be triggered when a memo has a side effect that causes its dependencies to change.
@@ -100,18 +100,18 @@ This will cause the memo to re-evaluate, which will then trigger the side effect
This can be avoided by using a [`createEffect`](/reference/basic-reactivity/create-effect) to handle the side effects instead:
```jsx
-import { createSignal, createMemo, createEffect } from "solid-js"
+import { createSignal, createMemo, createEffect } from "solid-js";
-const [count, setCount] = createSignal(0)
-const [message, setMessage] = createSignal("")
+const [count, setCount] = createSignal(0);
+const [message, setMessage] = createSignal("");
-const isEven = createMemo(() => count() % 2 === 0)
+const isEven = createMemo(() => count() % 2 === 0);
createEffect(() => {
if (count() > 10) {
- setMessage("Count is too high!")
+ setMessage("Count is too high!");
}
-})
+});
```
Here, the `createEffect` will handle the side effects, while the `isEven` memo will remain pure.
@@ -130,18 +130,18 @@ This separation of concerns can help keep your code clean and easy to understand
// effect - runs whenever `count` changes
createEffect(() => {
if (count() > 10) {
- setMessage("Count is too high!")
+ setMessage("Count is too high!");
} else {
- setMessage("")
+ setMessage("");
}
-})
+});
// memo - only runs when `count` changes to or from a value greater than 10
const message = createMemo(() => {
if (count() > 10) {
- return "Count is too high!"
+ return "Count is too high!";
} else {
- return ""
+ return "";
}
-})
+});
```
diff --git a/src/routes/concepts/effects.mdx b/src/routes/concepts/effects.mdx
index fe15500bdf..213fd8a4a0 100644
--- a/src/routes/concepts/effects.mdx
+++ b/src/routes/concepts/effects.mdx
@@ -88,9 +88,9 @@ setMessage("World"); // Output: 1, "World"
```
:::info
-When a signal updates, it notifies all of its subscribers sequentially but the *order can vary*.
+When a signal updates, it notifies all of its subscribers sequentially but the _order can vary_.
While effects are guaranteed to run when a signal updates, the execution might **not** be instantaneous.
-This means that the order of execution of effects is *not guaranteed* and should not be relied upon.
+This means that the order of execution of effects is _not guaranteed_ and should not be relied upon.
:::
### Nested effects
diff --git a/src/routes/concepts/intro-to-reactivity.mdx b/src/routes/concepts/intro-to-reactivity.mdx
index fa3e35fc28..156f15dd31 100644
--- a/src/routes/concepts/intro-to-reactivity.mdx
+++ b/src/routes/concepts/intro-to-reactivity.mdx
@@ -182,7 +182,8 @@ function Counter() {
return (
- Count: {count()}{/* β will update whenever `count()` changes. */}
+ Count: {count()}
+ {/* β will update whenever `count()` changes. */}
Increment
diff --git a/src/routes/concepts/refs.mdx b/src/routes/concepts/refs.mdx
index be36527bb4..17f44afe1b 100644
--- a/src/routes/concepts/refs.mdx
+++ b/src/routes/concepts/refs.mdx
@@ -20,16 +20,16 @@ JSX can be used as a value and assigned to a variable when looking to directly a
```tsx
function Component() {
- const myElement =
My Element
+ const myElement =
My Element
;
- return
{myElement}
+ return
{myElement}
;
}
```
This lets you create and access DOM elements similar to [`document.createElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) but without having to wait until it is attached to the DOM.
It can be used multiple times without having to worry about duplicate selectors.
-The downside of this approach is that it separates the element and any child elements from the rest of the JSX structure.
+The downside of this approach is that it separates the element and any child elements from the rest of the JSX structure.
This makes the component's JSX structure more difficult to read and understand.
## Refs in Solid
@@ -46,7 +46,7 @@ function Component() {
My Element
- )
+ );
}
```
@@ -54,9 +54,11 @@ These assignments occur at _creation time_ prior to the element being added to t
If access to an element is needed before it is added to the DOM, you can use the callback form of `ref`:
```jsx
-
{
- myElement = el // el is created but not yet added to the DOM
- }}>
+
{
+ myElement = el; // el is created but not yet added to the DOM
+ }}
+>
My Element
```
@@ -69,6 +71,7 @@ confirm it.
```tsx
let myElement!: HTMLDivElement;
```
+
:::
### Signals as refs
@@ -78,8 +81,8 @@ This is useful when you want to access the element directly, but the element may
```jsx
function App() {
- const [show, setShow] = createSignal(false)
- const [element, setElement] = createSignal()
+ const [show, setShow] = createSignal(false);
+ const [element, setElement] = createSignal();
return (
@@ -89,7 +92,7 @@ function App() {
This is the ref element
- )
+ );
}
```
@@ -114,21 +117,21 @@ To access the `ref` in the child component, it is passed as a prop:
```tsx
// Parent component
-import { Canvas } from "./Canvas.jsx"
+import { Canvas } from "./Canvas.jsx";
function ParentComponent() {
- let canvasRef
+ let canvasRef;
const animateCanvas = () => {
// Manipulate the canvas using canvasRef...
- }
+ };
return (
- )
+ );
}
```
@@ -158,8 +161,7 @@ Directives are like callback refs but they enable two extra features:
A directive is essentially a function with a specific signature:
```typescript
-function directive(element: Element, accessor: () => any): void
-
+function directive(element: Element, accessor: () => any): void;
```
- `element`: The DOM element that the directive is applied to.
diff --git a/src/routes/concepts/signals.mdx b/src/routes/concepts/signals.mdx
index d4558fe66b..c703d7f570 100644
--- a/src/routes/concepts/signals.mdx
+++ b/src/routes/concepts/signals.mdx
@@ -80,7 +80,7 @@ function Counter() {
```
:::info
-A tracking scope can be created by [`createEffect`](/reference/basic-reactivity/create-effect) or [`createMemo`](/reference/basic-reactivity/create-memo), which are other Solid primitives.
+A tracking scope can be created by [`createEffect`](/reference/basic-reactivity/create-effect) or [`createMemo`](/reference/basic-reactivity/create-memo), which are other Solid primitives.
Both functions subscribe to the signals accessed within them, establishing a dependency relationship.
Once this relationship is established, the function is notified whenever the signal changes.
diff --git a/src/routes/concepts/stores.mdx b/src/routes/concepts/stores.mdx
index 20ada72ab5..54af02bb98 100644
--- a/src/routes/concepts/stores.mdx
+++ b/src/routes/concepts/stores.mdx
@@ -15,7 +15,7 @@ Using JavaScript's [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScri
With stores, you can now target nested properties and elements within these structures to create a dynamic tree of reactive data.
```jsx
-import { createStore } from "solid-js/store"
+import { createStore } from "solid-js/store";
// Initialize store
const [store, setStore] = createStore({
@@ -40,7 +40,7 @@ const [store, setStore] = createStore({
loggedIn: true,
},
],
-})
+});
```
## Accessing store values
@@ -48,7 +48,7 @@ const [store, setStore] = createStore({
Store properties can be accessed directly from the state proxy through directly referencing the targeted property:
```jsx
-console.log(store.userCount) // Outputs: 3
+console.log(store.userCount); // Outputs: 3
```
Accessing stores within a tracking scope follows a similar pattern to signals.
@@ -57,7 +57,7 @@ This provides access to the store's value directly within a tracking scope:
```jsx
const App = () => {
- const [mySignal, setMySignal] = createSignal("This is a signal.")
+ const [mySignal, setMySignal] = createSignal("This is a signal.");
const [store, setStore] = createStore({
userCount: 3,
users: [
@@ -80,14 +80,14 @@ const App = () => {
loggedIn: true,
},
],
- })
+ });
return (
Hello, {store.users[0].username}
{/* Accessing a store value */}
{mySignal()} {/* Accessing a signal */}
- )
-}
+ );
+};
```
When a store is created, it starts with the initial state but does _not_ immediately set up signals to track changes.
@@ -97,7 +97,6 @@ Once data is used within a reactive context, such as within the return statement
For example, if you wanted to print out every new user, adding the console log below will not work because it is not within a tracked scope.
-
```tsx ins={9}
const App = () => {
const [store, setStore] = createStore({
@@ -199,7 +198,7 @@ Separating the read and write capabilities of a store provides a valuable debugg
This separation facilitates the tracking and control of the components that are accessing or changing the values.
:::
:::advanced
- A little hidden feature of stores is that you can also create nested stores to help with setting nested properties.
+A little hidden feature of stores is that you can also create nested stores to help with setting nested properties.
```jsx
const [store, setStore] = createStore({
@@ -220,9 +219,10 @@ This separation facilitates the tracking and control of the components that are
])
```
- Changes made through `setUsers` will update the `store.users` property and reading `users` from this derived store will also be in sync with the values from `store.users`.
- Note that the above relies on `store.users` to be set already in the existing store.
+Changes made through `setUsers` will update the `store.users` property and reading `users` from this derived store will also be in sync with the values from `store.users`.
+
+Note that the above relies on `store.users` to be set already in the existing store.
:::
@@ -265,7 +265,7 @@ setStore("users", (otherUsers) => [
location: "Nigeria",
loggedIn: false,
},
-])
+]);
// can become
@@ -274,7 +274,7 @@ setStore("users", store.users.length, {
username: "michael584",
location: "Nigeria",
loggedIn: false,
-})
+});
```
### Modifying multiple elements
@@ -287,11 +287,11 @@ For example, if `store.users` is an array of objects,
you can set the `loggedIn` property of several indices at once like so:
```jsx
-setStore("users", [2, 7, 10], "loggedIn", false)
+setStore("users", [2, 7, 10], "loggedIn", false);
// equivalent to (but more efficient than):
-setStore("users", 2, "loggedIn", false)
-setStore("users", 7, "loggedIn", false)
-setStore("users", 10, "loggedIn", false)
+setStore("users", 2, "loggedIn", false);
+setStore("users", 7, "loggedIn", false);
+setStore("users", 10, "loggedIn", false);
```
This array syntax also works for object property names.
@@ -299,10 +299,10 @@ For example, if `store.users` is an object mapping usernames to objects,
you can set the `loggedIn` property of several users at once like so:
```jsx
-setStore("users", ["me", "you"], "loggedIn", false)
+setStore("users", ["me", "you"], "loggedIn", false);
// equivalent to (but more efficient than):
-setStore("users", ["me"], "loggedIn", false)
-setStore("users", ["you"], "loggedIn", false)
+setStore("users", ["me"], "loggedIn", false);
+setStore("users", ["you"], "loggedIn", false);
```
For arrays specifically, you can specify a range of indices via an object
@@ -311,10 +311,10 @@ For example, assuming `store.users` is an array again,
you can set the `loggedIn` state for all users except index 0 as follows:
```jsx
-setStore("users", { from: 1, to: store.users.length - 1 }, "loggedIn", false)
+setStore("users", { from: 1, to: store.users.length - 1 }, "loggedIn", false);
// equivalent to (but more efficient than):
for (let i = 1; i <= store.users.length - 1; i++) {
- setStore("users", i, "loggedIn", false)
+ setStore("users", i, "loggedIn", false);
}
```
@@ -323,10 +323,15 @@ and thereby update a regular subset of elements.
For example, you can set the `loggedIn` state for even-indexed users like so:
```jsx
-setStore("users", { from: 0, to: store.users.length - 1, by: 2 }, "loggedIn", false)
+setStore(
+ "users",
+ { from: 0, to: store.users.length - 1, by: 2 },
+ "loggedIn",
+ false
+);
// equivalent to (but more efficient than):
for (let i = 1; i <= store.users.length - 1; i += 2) {
- setStore("users", i, "loggedIn", false)
+ setStore("users", i, "loggedIn", false);
}
```
@@ -342,7 +347,7 @@ These functions receive the old value as an argument, allowing you to compute th
This dynamic approach is particularly useful for complex transformations.
```jsx
-setStore("users", 3, "loggedIn" , (loggedIn) => !loggedIn)
+setStore("users", 3, "loggedIn", (loggedIn) => !loggedIn);
```
### Filtering values
@@ -352,7 +357,7 @@ This function will act as a filter, allowing you to select elements that satisfy
It receives the old value and index as arguments, providing the flexibility to make conditional updates.
```jsx
-setStore("users", (user) => user.username.startsWith("t"), "loggedIn", false)
+setStore("users", (user) => user.username.startsWith("t"), "loggedIn", false);
```
In addition to [`.startsWith`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith), you can use other array methods like [`.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) to filter for the values that you need.
@@ -367,14 +372,14 @@ What this means, is that you can directly make the change to the store _without_
```jsx
setStore("users", 0, {
id: 109,
-})
+});
// is equivalent to
setStore("users", 0, (user) => ({
...user,
id: 109,
-}))
+}));
```
## Store utilities
@@ -386,21 +391,21 @@ This utility provides a way to work with data as if it were a [mutable](https://
`produce` also provides a way to make changes to multiple properties at the same time which eliminates the need for multiple setter calls.
```jsx
-import { produce } from "solid-js/store"
+import { produce } from "solid-js/store";
// without produce
-setStore("users", 0, "username", "newUsername")
-setStore("users", 0, "location", "newLocation")
+setStore("users", 0, "username", "newUsername");
+setStore("users", 0, "location", "newLocation");
// with produce
setStore(
"users",
0,
produce((user) => {
- user.username = "newUsername"
- user.location = "newLocation"
+ user.username = "newUsername";
+ user.location = "newLocation";
})
-)
+);
```
`produce` and `setStore` do have distinct functionalities.
@@ -442,13 +447,13 @@ Additionally, `unwrap` provides a means to interface with third-party libraries
This utility acts as a bridge to facilitate smooth integrations with external components and simplifies the incorporation of stores into various applications and workflows.
```jsx
-import { createStore, unwrap } from "solid-js/store"
+import { createStore, unwrap } from "solid-js/store";
const [data, setData] = createStore({
animals: ["cat", "dog", "bird", "gorilla"],
-})
+});
-const rawData = unwrap(data)
+const rawData = unwrap(data);
```
To learn more about how to use Stores in practice, visit the [guide on complex state management](/guides/complex-state-management).
diff --git a/src/routes/concepts/understanding-jsx.mdx b/src/routes/concepts/understanding-jsx.mdx
index 357f0d0946..dd7e488634 100644
--- a/src/routes/concepts/understanding-jsx.mdx
+++ b/src/routes/concepts/understanding-jsx.mdx
@@ -12,7 +12,7 @@ This provides a concise and readable way to create and represent components.
Solid was designed to align closely with HTML standards.
```jsx
-const element =
I'm JSX!!
+const element =
I'm JSX!!
;
```
It offers a distinct advantage, however: to copy/paste solutions from resources like Stack Overflow; and to allow direct usage of templates from design tools.
@@ -21,14 +21,14 @@ This lets you use dynamic expressions within your HTML by allowing variables and
```jsx
const Component = () => {
- const animal = { breed: "cat", name: "Midnight" }
+ const animal = { breed: "cat", name: "Midnight" };
return (
I have a {animal.breed} named {animal.name}!
- )
-}
+ );
+};
```
This means JavaScript content can be rendered on web pages based on an application's state or logic.
@@ -98,6 +98,7 @@ In JSX files, HTML attributes are used much like regular HTML, with a few key di
Click me!
```
+
:::
### JSX properties (props)
@@ -110,17 +111,17 @@ They connect the component with the data it requires, for seamless data flows an
- **Static props**:
In Solid's JSX, static props are integrated directly into the HTML by cloning the template and using them as attributes.
- - **Dynamic props**:
- Dynamic props rely on state, allowing the content or properties to be dynamic.
- An example is changing the style of an element in response to interactions within an application.
- This can be expressed in the form of signals (`value={value()}`).
+- **Dynamic props**:
+ Dynamic props rely on state, allowing the content or properties to be dynamic.
+ An example is changing the style of an element in response to interactions within an application.
+ This can be expressed in the form of signals (`value={value()}`).
- **Data transfer**:
Props are also used to fill components with data that comes from resources, like [`createResource`](/reference/basic-reactivity/create-resource) calls.
This results in components that react in real-time to data changes.
:::info
-Expressions, whether fixed or dynamic, get applied *in the order defined within the JSX*.
+Expressions, whether fixed or dynamic, get applied _in the order defined within the JSX_.
This works for a wide range of DOM elements, but will not work with elements that require attributes to be defined in a special order, such as input types with `type='range'`.
When order influences an element's behavior, users must define the expressions in the order that the element is expected.
diff --git a/src/routes/configuration/environment-variables.mdx b/src/routes/configuration/environment-variables.mdx
index 37537a5eea..4ec0256781 100644
--- a/src/routes/configuration/environment-variables.mdx
+++ b/src/routes/configuration/environment-variables.mdx
@@ -62,8 +62,8 @@ function MyComponent() {
These variables should only be accessed in your backend code, so it's best not to use the `VITE_` prefix for them. Instead, use `process.env` to access them. Depending on the [Nitro preset](https://nitro.build/deploy) chosen, they'll be made available automatically or they will require an external dependency such as [dotenv](https://www.npmjs.com/package/dotenv).
```jsx
-DB_HOST="somedb://192.110.0"
-DB_PASSWORD = super_secret_password_hash
+DB_HOST = "somedb://192.110.0";
+DB_PASSWORD = super_secret_password_hash;
```
To access them, within your backend code, use `process.env`.
@@ -82,11 +82,10 @@ For an example, check the pseudo-code below.
It is also possible to make `process.env` type-safe via the same `.env.d.ts` file.
```typescript
-
declare namespace NodeJS {
interface ProcessEnv {
- readonly DB_URL: string
- readonly DB_PASSWORD: string
+ readonly DB_URL: string;
+ readonly DB_PASSWORD: string;
}
}
```
diff --git a/src/routes/configuration/typescript.mdx b/src/routes/configuration/typescript.mdx
index 059120a92c..8f7fab9f20 100644
--- a/src/routes/configuration/typescript.mdx
+++ b/src/routes/configuration/typescript.mdx
@@ -59,17 +59,9 @@ npm i --save-dev typescript
```
```bash frame="none"
@@ -421,9 +405,9 @@ function MyGenericComponent(props: MyProps): JSX.Element {
```
:::info
- Each `Component` type has a corresponding `Props` type that defines the shape
- of its properties. These `Props` types also accept the same generic types as
- their associated `Component` types.
+Each `Component` type has a corresponding `Props` type that defines the shape
+of its properties. These `Props` types also accept the same generic types as
+their associated `Component` types.
:::
### Event handling
@@ -523,13 +507,13 @@ return
...
In this case, using `divRef!` within the `ref` attribute signals to TypeScript that `divRef` will receive an assignment after this stage, which is more in line with how Solid works.
:::info
- While TypeScript does catch incorrect usage of refs that occur before their
- JSX block definition, it currently does not identify undefined variables
- within certain nested functions in Solid. Therefore, additional care is needed
- when using `ref`s in functions such as
- [`createMemo`](/reference/basic-reactivity/create-memo),
- [`createRenderEffect`](/reference/secondary-primitives/create-render-effect),
- and [`createComputed`](/reference/secondary-primitives/create-computed).
+While TypeScript does catch incorrect usage of refs that occur before their
+JSX block definition, it currently does not identify undefined variables
+within certain nested functions in Solid. Therefore, additional care is needed
+when using `ref`s in functions such as
+[`createMemo`](/reference/basic-reactivity/create-memo),
+[`createRenderEffect`](/reference/secondary-primitives/create-render-effect),
+and [`createComputed`](/reference/secondary-primitives/create-computed).
:::
Finally, a riskier approach involves using the definite assignment assertion right at the point of variable initialization.
@@ -584,9 +568,9 @@ return
- )
+ );
}}
>
- )
-}
+ );
+};
-export default App
+export default App;
```
There are several challenges to managing state in this way:
@@ -96,16 +98,16 @@ If you're new to the concept of stores, see the [stores section](/concepts/store
To reduce the amount of signals that were used in the original example, you can do the following using a store:
```jsx
-import { createStore } from "solid-js/store"
+import { createStore } from "solid-js/store";
const App = () => {
const [state, setState] = createStore({
tasks: [],
numberOfTasks: 0,
- })
-}
+ });
+};
-export default App
+export default App;
```
Through using a store, you no longer need to keep track of separate signals for `tasks`, `numberOfTasks`, and `completedTasks`.
@@ -115,22 +117,22 @@ Through using a store, you no longer need to keep track of separate signals for
Once you have created your store, the values can be accessed directly through the first value returned by the `createStore` function:
```jsx
-import { createStore } from "solid-js/store"
+import { createStore } from "solid-js/store";
const App = () => {
const [state, setState] = createStore({
tasks: [],
numberOfTasks: 0,
- })
+ });
return (
<>
My Task List for Today
You have {state.numberOfTasks} task(s) for today!
>
- )
-}
+ );
+};
-export default App
+export default App;
```
Through `state.numberOfTasks`, the display will now show the store's value held in the `numberOfTasks` property.
@@ -144,12 +146,12 @@ To create the signal so it reactively updates, you have to access the property w
```jsx
// not reactive
-setState("numberOfTasks", state.tasks.length)
+setState("numberOfTasks", state.tasks.length);
// reactive
createEffect(() => {
- setState("numberOfTasks", state.tasks.length)
-})
+ setState("numberOfTasks", state.tasks.length);
+});
```
### Adding to an array
@@ -163,8 +165,8 @@ const addTask = (text) => {
id: state.tasks.length,
text,
completed: false,
- })
-}
+ });
+};
```
The setter in stores follow [path syntax](/concepts/stores#path-syntax-flexibility): `setStore("key", value)`.
@@ -178,40 +180,40 @@ Something such as toggle function:
```jsx
const toggleTask = (id) => {
- const currentCompletedStatus = state.tasks[id].completed
+ const currentCompletedStatus = state.tasks[id].completed;
setState(
"tasks",
(task) => task.id === id,
"completed",
!currentCompletedStatus
- )
-}
+ );
+};
```
Can be simplified using `produce`:
```jsx
-import { produce } from "solid-js/store"
+import { produce } from "solid-js/store";
const toggleTask = (id) => {
setState(
"tasks",
(tasks) => tasks.id === id,
produce((task) => {
- task.completed = !task.completed
+ task.completed = !task.completed;
})
- )
-}
+ );
+};
// You can also rewrite the `addTask` function through produce
const addTask = (text) => {
setState(
"tasks",
produce((task) => {
- task.push({ id: state.tasks.length, text, completed: false })
+ task.push({ id: state.tasks.length, text, completed: false });
})
- )
-}
+ );
+};
```
Read about some of the other [advantages to using `produce`](/concepts/stores#store-updates-with-produce).
@@ -222,9 +224,9 @@ Read about some of the other [advantages to using `produce`](/concepts/stores#st
```jsx
// without produce
batch(() => {
- setState(0, "text", "I'm updated text")
- setState(0, "completed", true)
-})
+ setState(0, "text", "I'm updated text");
+ setState(0, "completed", true);
+});
// with produce
setState(
@@ -233,7 +235,7 @@ setState(
task.text = "I'm updated text";
task.completed = true;
})
-)
+);
```
:::
@@ -241,37 +243,37 @@ setState(
The updated example:
```jsx
-import { For, createEffect, Show } from "solid-js"
-import { createStore, produce } from "solid-js/store"
+import { For, createEffect, Show } from "solid-js";
+import { createStore, produce } from "solid-js/store";
const App = () => {
- let input // lets you target the input value
+ let input; // lets you target the input value
const [state, setState] = createStore({
tasks: [],
numberOfTasks: 0,
- })
+ });
const addTask = (text) => {
setState("tasks", state.tasks.length, {
id: state.tasks.length,
text,
completed: false,
- })
- }
+ });
+ };
const toggleTask = (id) => {
setState(
"tasks",
(tasks) => tasks.id === id,
produce((task) => {
- task.completed = !task.completed
+ task.completed = !task.completed;
})
- )
- }
+ );
+ };
createEffect(() => {
- setState("numberOfTasks", state.tasks.length)
- })
+ setState("numberOfTasks", state.tasks.length);
+ });
return (
<>
@@ -282,16 +284,16 @@ const App = () => {
{
- if (!input.value.trim()) return
- addTask(input.value)
- input.value = ""
+ if (!input.value.trim()) return;
+ addTask(input.value);
+ input.value = "";
}}
>
Add Task
{(task) => {
- const { id, text } = task
+ const { id, text } = task;
return (
{
/>
{text}
- )
+ );
}}
>
- )
-}
+ );
+};
-export default App
+export default App;
```
## State sharing
@@ -322,40 +324,40 @@ To use this, you need to create a context.
This context will have a default value and can be consumed by any _descendant_ component.
```jsx
-import { createContext } from "solid-js"
+import { createContext } from "solid-js";
-const TaskContext = createContext()
+const TaskContext = createContext();
```
Your components will be wrapped with the `Provider` from the context, and passed with the values that you wish to share.
```jsx
-import { createStore } from "solid-js/store"
+import { createStore } from "solid-js/store";
const TaskApp = () => {
const [state, setState] = createStore({
tasks: [],
numberOfTasks: 0,
- })
+ });
return (
{/* Your components */}
- )
-}
+ );
+};
```
In any descendent component, you can consume the context values using `useContext`:
```jsx
-import { useContext } from "solid-js"
+import { useContext } from "solid-js";
const TaskList = () => {
- const { state, setState } = useContext(TaskContext)
+ const { state, setState } = useContext(TaskContext);
// Now you can use the shared state and functions
-}
+};
```
For a deeper dive, please refer to our dedicated [page on context](/concepts/context).
diff --git a/src/routes/guides/data.json b/src/routes/guides/data.json
index 364f3f925c..b31c852583 100644
--- a/src/routes/guides/data.json
+++ b/src/routes/guides/data.json
@@ -7,7 +7,7 @@
"routing-and-navigation.mdx",
"complex-state-management.mdx",
"fetching-data.mdx",
- "testing.mdx",
+ "testing.mdx",
"deploying-your-app.mdx",
"deployment-options"
]
diff --git a/src/routes/guides/deployment-options/aws-via-sst.mdx b/src/routes/guides/deployment-options/aws-via-sst.mdx
index 4a59999bd6..96d3b58b1c 100644
--- a/src/routes/guides/deployment-options/aws-via-sst.mdx
+++ b/src/routes/guides/deployment-options/aws-via-sst.mdx
@@ -4,7 +4,7 @@ order: 1
mainNavExclude: true
---
-[SST](https://sst.dev/) is a framework for deploying applications to any cloud provider. It has a built-in way to deploy SolidStart apps to AWS Lambda. For additional details, you can [visit their docs](https://sst.dev/docs/).
+[SST](https://sst.dev/) is a framework for deploying applications to any cloud provider. It has a built-in way to deploy SolidStart apps to AWS Lambda. For additional details, you can [visit their docs](https://sst.dev/docs/).
## Quick start
@@ -13,59 +13,35 @@ mainNavExclude: true
2. In your project, init SST.
-
3. This will detect your SolidStart app and ask you to update your `app.config.ts`.
```ts title="app.config.ts"
server: {
- preset: "aws-lambda-streaming"
+ preset: "aws-lambda-streaming";
}
```
4. When you are ready, you can deploy your app using:
-
-```bash frame="none"
-npx sst@latest deploy --stage production
-```
-
-
-```bash frame="none"
-yarn dlx sst@latest deploy --stage production
-```
-
-
-```bash frame="none"
-pnpm dlx sst@latest deploy --stage production
-```
-
-
-```bash frame="none"
-bunx sst@latest deploy --stage production
-```
-
+
+ ```bash frame="none" npx sst@latest deploy --stage production ```
+
+ ```bash frame="none" bunx sst@latest deploy --stage production ```
+
You can [read the full tutorial on the SST docs](https://sst.dev/docs/start/aws/solid).
diff --git a/src/routes/guides/deployment-options/cloudflare.mdx b/src/routes/guides/deployment-options/cloudflare.mdx
index 5a1474b033..a08c0d232c 100644
--- a/src/routes/guides/deployment-options/cloudflare.mdx
+++ b/src/routes/guides/deployment-options/cloudflare.mdx
@@ -65,17 +65,9 @@ npm i -g wrangler
```
-
-```bash frame="none"
-yarn global add wrangler
-```
-
```bash frame="none"
diff --git a/src/routes/guides/deployment-options/stormkit.mdx b/src/routes/guides/deployment-options/stormkit.mdx
index 3c8b997493..74b47c1a56 100644
--- a/src/routes/guides/deployment-options/stormkit.mdx
+++ b/src/routes/guides/deployment-options/stormkit.mdx
@@ -14,7 +14,7 @@ mainNavExclude: true
4. Verify the build command in your Stormkit configuration. By default, Stormkit CI will run `npm run build` but you can specify a custom build command on this page.
-5. Check output folder, unless its specified Stormkit will try to upload contents of build folder.
+5. Check output folder, unless its specified Stormkit will try to upload contents of build folder.
6. Click the βDeploy Nowβ button to deploy your site. Stormkit CI will build your code and upload contents of it.
diff --git a/src/routes/guides/deployment-options/vercel.mdx b/src/routes/guides/deployment-options/vercel.mdx
index 7e7beb7765..0b5bb6875d 100644
--- a/src/routes/guides/deployment-options/vercel.mdx
+++ b/src/routes/guides/deployment-options/vercel.mdx
@@ -58,17 +58,9 @@ npm i -g vercel
```
-
-```bash frame="none"
-yarn global add vercel
-```
-
+
```bash frame="none" yarn global add vercel ```
-
-```bash frame="none"
-pnpm add -g vercel
-```
-
+
```bash frame="none" pnpm add -g vercel ```
```bash frame="none"
diff --git a/src/routes/guides/deployment-options/zerops.mdx b/src/routes/guides/deployment-options/zerops.mdx
index f9d953bb18..6e8ce8055d 100644
--- a/src/routes/guides/deployment-options/zerops.mdx
+++ b/src/routes/guides/deployment-options/zerops.mdx
@@ -11,6 +11,7 @@ import { TabsCodeBlocks } from "~/ui/tab-code-blocks";
For additional one-to-one support, details, and features, you can join the [Zerops Discord server](https://discord.gg/xxzmJSDKPT) and [visit the Zerops Docs](https://docs.zerops.io).
Deploy and test Zerops Solid recipes with one click:
+
- [Deploy Solid Node.js & Static Together](https://app.zerops.io/recipe/solidjs) - [Node.js](https://github.com/zeropsio/recipe-solidjs-nodejs) and [Static](https://github.com/zeropsio/recipe-solidjs-static).
- [Deploy Solid Node.js](https://app.zerops.io/recipe/solidjs-nodejs) - [Source Repository](https://github.com/zeropsio/recipe-solidjs-nodejs)
- [Deploy Solid Static](https://app.zerops.io/recipe/solidjs-static) - [Source Repository](https://github.com/zeropsio/recipe-solidjs-static)
@@ -30,11 +31,13 @@ There are two ways to set up a Zerops project and a service:
3. You'll be redirected to a page where you can choose a service.
##### For Static:
+
1. Choose Static.
2. Scroll down and change the hostname to your preference.
3. Scroll down and click on the "Add New Static" button.
##### For SSR - Node.js:
+
1. Choose `Node.js` and select `version 20`.
2. Scroll down and change the hostname to your preference.
3. Scroll down and click on the "Add New Node.js" button.
@@ -46,6 +49,7 @@ There are two ways to set up a Zerops project and a service:
1. Go to your [Zerops dashboard](https://app.zerops.io/dashboard/projects) and click on your profile icon if you are a new user. If not, check your sidebar and click on `Import Project`.
##### Static:
+
```yaml
project:
name: recipe-solidjs
@@ -57,6 +61,7 @@ services:
```
##### SSR - Node.js:
+
```yaml
project:
name: recipe-solidjs
@@ -68,6 +73,7 @@ services:
```
## Add zerops.yml to your repository
+
The `zerops.yml` configuration file is used to tell Zerops how to build and run your application, it should be placed to the root of your appplication's repository.
Example for **SSR (Server-Side Rendering)** Apps:
@@ -112,18 +118,19 @@ zerops:
run:
base: static
```
+
Push the changes to your GitHub/GitLab repository (necessary if you are planning to use GitHub/GitLab).
## Deploying your apps
### Triggering the pipeline automatically by connecting Github/Gitlab repository
-You can push your project by [Triggering the pipeline using Zerops CLI](#triggering-the-pipeline-using-githubgitlab) or by connecting the app service with your [GitHub](https://docs.zerops.io/references/github-integration/) / [GitLab](https://docs.zerops.io/references/gitlab-integration) repository from inside the service detail.
-
+You can push your project by [Triggering the pipeline using Zerops CLI](#triggering-the-pipeline-using-githubgitlab) or by connecting the app service with your [GitHub](https://docs.zerops.io/references/github-integration/) / [GitLab](https://docs.zerops.io/references/gitlab-integration) repository from inside the service detail.
### Triggering the pipeline manually using Zerops CLI
To download the zCLI binary directly, use [zCLI/releases](https://github.com/zeropsio/zcli/releases) or:
+
1. Install the Zerops CLI using Terminal.
Linux/MacOS
@@ -139,30 +146,22 @@ irm https://zerops.io/zcli/install.ps1 | iex
```
Npm
+
-
-```bash frame="none"
-npm i -g @zerops/zcli
-```
-
-```bash frame="none"
-yarn global add @zerops/zcli
-```
-
+
```bash frame="none" npm i -g @zerops/zcli ```
+
```bash frame="none" pnpm add -g @zerops/zcli ```
+
```bash frame="none" yarn global add @zerops/zcli ```
2. Open Settings > [Access Token Management](https://app.zerops.io/settings/token-management) in the Zerops app and generate a new access token.
3. Log in using your access token with the following command:
+
```bash
zcli login
```
+
4. Navigate to the root of your app (where zerops.yml is located) and run the following command in Terminal to trigger the deploy:
+
```bash
zcli push
```
diff --git a/src/routes/guides/fetching-data.mdx b/src/routes/guides/fetching-data.mdx
index 8bf0f9e24e..096c1f195f 100644
--- a/src/routes/guides/fetching-data.mdx
+++ b/src/routes/guides/fetching-data.mdx
@@ -23,11 +23,12 @@ These properties can be used to conditionally render JSX based on the current re
The fetcher function that is created makes a call to get a user, which is then passed in as an argument to `createResource`.
The signal returned from the `createResource` provides the properties that can assist with conditional rendering based on the current reactive state:
-* `state`: The current status of the operation (`unresolved`, `pending`, `ready`, `refreshing`, or `errored`).
-* `loading`: Indicates that the operation is currently in progress via a `boolean`.
-* `error`: If the operation fails for any reason, this property will contain information about this error.
-It may be a string with an error message, or an object with more detailed information.
-* `latest`: The most recent data or result returned from the operation.
+
+- `state`: The current status of the operation (`unresolved`, `pending`, `ready`, `refreshing`, or `errored`).
+- `loading`: Indicates that the operation is currently in progress via a `boolean`.
+- `error`: If the operation fails for any reason, this property will contain information about this error.
+ It may be a string with an error message, or an object with more detailed information.
+- `latest`: The most recent data or result returned from the operation.
When there is a change in the source signal, an internal fetch process is triggered to retrieve new data based on this change.
@@ -35,35 +36,35 @@ When there is a change in the source signal, an internal fetch process is trigge
import { createSignal, createResource, Switch, Match, Show } from "solid-js";
const fetchUser = async (id) => {
- const response = await fetch(`https://swapi.dev/api/people/${id}/`);
- return response.json();
-}
+ const response = await fetch(`https://swapi.dev/api/people/${id}/`);
+ return response.json();
+};
function App() {
- const [userId, setUserId] = createSignal();
- const [user] = createResource(userId, fetchUser);
-
- return (
-
+ );
}
```
@@ -77,12 +78,11 @@ However, if there's an error while fetching, the `user.error` block becomes `tru
:::tip
If you anticipate errors, you may want to wrap `createResource` in an [ErrorBoundary](/reference/components/error-boundary).
-
+
:::
In addition to the `error` property, the `loading` property offers a way to display a loading state to the user during the fetch operation.
-
## Calling multiple async events
Although you can use `createResource` independently, Solid provides an alternative method for synchronizing the display of multiple asynchronous events.
@@ -90,37 +90,43 @@ Although you can use `createResource` independently, Solid provides an alternati
It allows you to display a fallback placeholder while waiting for all asynchronous events to resolve, preventing the display of partially loaded content:
```jsx
-import { createSignal, createResource, Switch, Match, Suspense } from "solid-js";
+import {
+ createSignal,
+ createResource,
+ Switch,
+ Match,
+ Suspense,
+} from "solid-js";
const fetchUser = async (id) => {
- const response = await fetch(`https://swapi.dev/api/people/${id}/`);
- return response.json();
-}
+ const response = await fetch(`https://swapi.dev/api/people/${id}/`);
+ return response.json();
+};
function App() {
- const [userId, setUserId] = createSignal();
- const [user] = createResource(userId, fetchUser);
-
- return (
-
+ );
}
```
@@ -146,30 +152,26 @@ This functionality is particularly valuable in applications like task lists.
For example, when users input a new task and click the `Add` button, the list will refresh immediately, regardless of the ongoing data communication with the server.
```jsx
-import { For, createResource } from "solid-js"
+import { For, createResource } from "solid-js";
function TodoList() {
- const [tasks, { mutate }] = createResource(fetchTasksFromServer);
-
- return (
- <>
-
-
- {(task) => (
-
{task.name}
- )}
-
-
- {
- mutate((todos) => [...todos, "do new task"]); // add todo for user
- // make a call to send to database
- }}
- >
- Add Task
-
- >
- );
+ const [tasks, { mutate }] = createResource(fetchTasksFromServer);
+
+ return (
+ <>
+
+ {(task) =>
{task.name}
}
+
+ {
+ mutate((todos) => [...todos, "do new task"]); // add todo for user
+ // make a call to send to database
+ }}
+ >
+ Add Task
+
+ >
+ );
}
```
@@ -179,14 +181,14 @@ When real-time feedback is necessary, the `refetch` method can be used to reload
This method can be particularly useful when data is constantly evolving, such as with real-time financial applications.
```jsx
-import { createResource, onCleanup } from "solid-js"
+import { createResource, onCleanup } from "solid-js";
function StockPriceTicker() {
- const [prices, { refetch }] = createResource(fetchStockPrices);
+ const [prices, { refetch }] = createResource(fetchStockPrices);
- const timer = setInterval(() => {
- refetch()
- }, 1000);
- onCleanup(() => clearInterval(timer))
+ const timer = setInterval(() => {
+ refetch();
+ }, 1000);
+ onCleanup(() => clearInterval(timer));
}
```
diff --git a/src/routes/guides/routing-and-navigation.mdx b/src/routes/guides/routing-and-navigation.mdx
index 73aacadda3..d90f630578 100644
--- a/src/routes/guides/routing-and-navigation.mdx
+++ b/src/routes/guides/routing-and-navigation.mdx
@@ -20,17 +20,9 @@ npm install @solidjs/router
```
```bash frame="none"
@@ -492,8 +484,8 @@ The value of a preload function is passed to the page component when called at a
This means you can initialize the page, or use [Data APIs](/solid-router/reference/data-apis/create-async).
:::info
- To prevent a fetch from happening more than once, or to trigger a refetch, you
- can use the [`query` function](/solid-router/reference/data-apis/query).
+To prevent a fetch from happening more than once, or to trigger a refetch, you
+can use the [`query` function](/solid-router/reference/data-apis/query).
:::
```jsx title="index.jsx"
diff --git a/src/routes/guides/state-management.mdx b/src/routes/guides/state-management.mdx
index 5f5113fbc0..00170aef81 100644
--- a/src/routes/guides/state-management.mdx
+++ b/src/routes/guides/state-management.mdx
@@ -161,7 +161,7 @@ Derived values can be created using a signal within a function, which can be ref
This approach can be used to simplify the `doubleCount` example above, where the additional signal and effect can be replaced with a derived signal:
```jsx del={5, 11-13} ins={15}
-import { createSignal } from "solid-js"
+import { createSignal } from "solid-js";
function Counter() {
const [count, setCount] = createSignal(0);
@@ -175,7 +175,7 @@ function Counter() {
setDoubleCount(count() * 2); // Update doubleCount whenever count changes
});
- const doubleCount = () => count() * 2
+ const doubleCount = () => count() * 2;
return (
<>
@@ -192,20 +192,20 @@ While this approach works for simple use cases, if `doubleCount` is used several
The derived signal would be re-evaluated not just each time `count` is changed, but also for each use of `doubleCount()`.
```jsx del={10} ins={11-14, 20-21}
-import { createSignal } from "solid-js"
+import { createSignal } from "solid-js";
function Counter() {
- const [count, setCount] = createSignal(0)
+ const [count, setCount] = createSignal(0);
const increment = () => {
- setCount(count() + 1)
- }
+ setCount(count() + 1);
+ };
- const doubleCount = () => count() * 2
+ const doubleCount = () => count() * 2;
const doubleCount = () => {
- console.log('doubleCount called')
- return count() * 2
- }
+ console.log("doubleCount called");
+ return count() * 2;
+ };
return (
<>
@@ -215,7 +215,7 @@ function Counter() {
Doubled count: {doubleCount()}
Increment
>
- )
+ );
}
```
@@ -231,24 +231,24 @@ When using a memo, the calculation will only run **once** when the value of `cou
Using the [`createMemo`](/reference/basic-reactivity/create-memo) function, you can create a memoized value:
```jsx ins={15-18, 26-28} ins=", createMemo"
-import { createSignal, createMemo } from "solid-js"
+import { createSignal, createMemo } from "solid-js";
function Counter() {
- const [count, setCount] = createSignal(0)
+ const [count, setCount] = createSignal(0);
const increment = () => {
setCount((prev) => prev + 1);
};
const doubleCount = () => {
- console.log('doubleCount called')
- return count() * 2
- }
+ console.log("doubleCount called");
+ return count() * 2;
+ };
const doubleCountMemo = createMemo(() => {
- console.log('doubleCountMemo called')
- return count() * 2
- })
+ console.log("doubleCountMemo called");
+ return count() * 2;
+ });
return (
<>
diff --git a/src/routes/guides/styling-components/less.mdx b/src/routes/guides/styling-components/less.mdx
index ba92f217c4..b877a2845f 100644
--- a/src/routes/guides/styling-components/less.mdx
+++ b/src/routes/guides/styling-components/less.mdx
@@ -18,17 +18,9 @@ npm i --save-dev less
```
@@ -36,7 +32,6 @@ bun add @macaron-css/core @macaron-css/solid
-
2. Within your `vite.config.js` folder, add the macaron plugin prior to other plugins:
```js
diff --git a/src/routes/guides/styling-components/sass.mdx b/src/routes/guides/styling-components/sass.mdx
index cbf5326780..4ee234fea9 100644
--- a/src/routes/guides/styling-components/sass.mdx
+++ b/src/routes/guides/styling-components/sass.mdx
@@ -18,17 +18,9 @@ npm i --save-dev sass
```
```bash frame="none"
diff --git a/src/routes/guides/styling-components/tailwind.mdx b/src/routes/guides/styling-components/tailwind.mdx
index 32dc3057b4..69e97e9012 100644
--- a/src/routes/guides/styling-components/tailwind.mdx
+++ b/src/routes/guides/styling-components/tailwind.mdx
@@ -10,7 +10,7 @@ This guide is for Tailwind CSS v4. For **Tailwind CSS v3** refer to [Tailwind CS
-[Tailwind CSS](https://tailwindcss.com/) is an on-demand utility CSS library that integrates seamlessly with Solid as a built-in PostCSS plugin.
+[Tailwind CSS](https://tailwindcss.com/) is an on-demand utility CSS library that integrates seamlessly with Solid as a built-in PostCSS plugin.
## Installation
@@ -53,8 +53,8 @@ bun add --save-dev tailwindcss @tailwindcss/postcss postcss
export default {
plugins: {
"@tailwindcss/postcss": {},
- }
-}
+ },
+};
```
For a deeper dive into configuration, you can check out the [Tailwind Official Documentation](https://tailwindcss.com/docs/configuration).
@@ -67,7 +67,6 @@ Add an `@import` to your `src/index.css` file that imports Tailwind CSS.
@import "tailwindcss";
```
-
## Import your CSS file
Import your `index.css` file into the root `index.jsx` or `index.tsx` file:
diff --git a/src/routes/guides/styling-components/uno.mdx b/src/routes/guides/styling-components/uno.mdx
index 37b4a99b37..bc4f5d7107 100644
--- a/src/routes/guides/styling-components/uno.mdx
+++ b/src/routes/guides/styling-components/uno.mdx
@@ -9,6 +9,7 @@ mainNavExclude: true
## Install Vite plugin
To get started with UnoCSS in your Solid app:
+
```bash frame="none"
diff --git a/src/routes/guides/testing.mdx b/src/routes/guides/testing.mdx
index d0a1001c6e..253b40918e 100644
--- a/src/routes/guides/testing.mdx
+++ b/src/routes/guides/testing.mdx
@@ -15,29 +15,25 @@ Testing your Solid applications is important to inspiring confidence in your cod
- [`@testing-library/user-event`](https://testing-library.com/docs/user-event/intro) - used to simulate user events that are closer to reality
- [`@testing-library/jest-dom`](https://testing-library.com/docs/ecosystem-jest-dom) - augments expect with helpful matchers
-
### Adding testing packages
-The recommended testing framework for Solid applications is [vitest](https://vitest.dev).
+The recommended testing framework for Solid applications is [vitest](https://vitest.dev).
To get started with vitest, install the following development dependencies:
-
@@ -134,21 +132,9 @@ The [`expect` function provided by `vitest`](https://vitest.dev/api/expect.html)
To run this test, use the following command:
-
-```bash frame="none"
-npm test
-```
-
-
-```bash frame="none"
-yarn test
-```
-
-
-```bash frame="none"
-pnpm test
-```
-
+
```bash frame="none" npm test ```
+
```bash frame="none" yarn test ```
+
```bash frame="none" pnpm test ```
If running the command is successful, you will get the following result showing whether the tests have passed or failed:
@@ -170,30 +156,31 @@ environment 880ms, prepare 212ms)
#### Rendering the component
-The `render` function from `@solidjs/testing-library` creates the testing environment within the `test.tsx` file.
+The `render` function from `@solidjs/testing-library` creates the testing environment within the `test.tsx` file.
It sets up the container, rendering the component within it, and automatically registers it for clean-up after a successful test.
Additionally, it manages wrapping the component in contexts as well as setting up a router.
```tsx frame="none"
const renderResult = render(
- () => , // @solidjs/testing-library requires a function
- { // all options are optional
- container, // manually set up your own container, will not be handled
- baseElement, // parent of container in case it is not supplied
- queries, // manually set up custom queries
- hydrate, // set to `true` to use hydration
- wrapper, // reusable wrapper component to supply context
- location, // sets up a router pointed to the location if provided
- }
-)
+ () => , // @solidjs/testing-library requires a function
+ {
+ // all options are optional
+ container, // manually set up your own container, will not be handled
+ baseElement, // parent of container in case it is not supplied
+ queries, // manually set up custom queries
+ hydrate, // set to `true` to use hydration
+ wrapper, // reusable wrapper component to supply context
+ location, // sets up a router pointed to the location if provided
+ }
+);
const {
- asFragment, // function returning the contents of the container
- baseElement, // the parent of the container
- container, // the container in which the component is rendered
- debug, // a function giving some helpful debugging output
- unmount, // manually removing the component from the container
- ...queries, // functions to select elements from the container
-} = renderResult
+ asFragment, // function returning the contents of the container
+ baseElement, // the parent of the container
+ container, // the container in which the component is rendered
+ debug, // a function giving some helpful debugging output
+ unmount, // manually removing the component from the container
+ ...queries // functions to select elements from the container
+} = renderResult;
```
##### Using the right queries
@@ -223,7 +210,7 @@ If there are multiple elements matching the same query, `getAllBy...` should be
There are two exceptions when you should **not** start with `get...`:
1. If the `location` option is used or the component is based on resources, the router will be lazy-loaded; in this case, the first query after rendering needs to be `find...`
-2. When testing something that is *not* rendered, you will need to find something that will be rendered at the same time; after that, use `queryAllBy...` to test if the result is an empty array (`[]`).
+2. When testing something that is _not_ rendered, you will need to find something that will be rendered at the same time; after that, use `queryAllBy...` to test if the result is an empty array (`[]`).
The query's suffix (Role, LabelText, ...) depends on the characteristics of the element you want to select.
If possible, try to select for accessible attributes (roughly in the following order):
@@ -235,7 +222,7 @@ If possible, try to select for accessible attributes (roughly in the following o
- **DisplayValue**: form elements showing the given value (e.g. select elements)
- **AltText**: images with alt text
- **Title**: HTML elements with the `title` attribute or SVGs with the `` tag containing the given text
-- **TestId**: queries by the `data-testid` attribute; a different data attribute can be setup via `configure({testIdAttribute: 'data-my-test-attribute'})`; TestId-queries are *not accessible*, so use them only as a last resort.
+- **TestId**: queries by the `data-testid` attribute; a different data attribute can be setup via `configure({testIdAttribute: 'data-my-test-attribute'})`; TestId-queries are _not accessible_, so use them only as a last resort.
For more information, check the [testing-library documentation](https://testing-library.com/docs/queries/about).
@@ -251,11 +238,12 @@ import { render, screen } from "@solidjs/testing-library"
import { Toast } from "./Toast"
test("increments value", async () => {
- render(() =>
This is a toast
)
- const toast = screen.getByRole("log")
- expect(toast).toHaveTextContent("This is a toast")
+render(() =>
This is a toast
)
+const toast = screen.getByRole("log")
+expect(toast).toHaveTextContent("This is a toast")
})
-```
+
+````
@@ -279,15 +268,15 @@ export const Toast = (props) => {
If a component relies on some context, to wrap it use the `wrapper` option:
```tsx title="Context.test.tsx"
-import { test, expect } from "vitest"
-import { render } from "@solidjs/testing-library"
-import { DataContext, DataConsumer } from "./Data"
+import { test, expect } from "vitest";
+import { render } from "@solidjs/testing-library";
+import { DataContext, DataConsumer } from "./Data";
-const wrapper = (props) =>
+const wrapper = (props) => ;
test("receives data from context", () => {
- const { getByText } = render(() => , { wrapper })
- expect(getByText("test")).toBeInTheDocument()
+ const { getByText } = render(() => , { wrapper });
+ expect(getByText("test")).toBeInTheDocument();
});
```
@@ -295,8 +284,9 @@ Wrappers can be re-used if they are created externally.
For wrappers with different values, a higher-order component creating the required wrappers can make the tests more concise:
```tsx
-const createWrapper = (value) => (props) =>
-
+const createWrapper = (value) => (props) => (
+
+);
```
:::info[Using multiple providers]
@@ -310,10 +300,10 @@ Since the `` component is lazily loaded, the first query after rendering
```tsx
const { findByText } = render(
- () => ,
- { location: "/article/12345" }
+ () => ,
+ { location: "/article/12345" }
);
-expect(await findByText("Article 12345")).toBeInTheDocument()
+expect(await findByText("Article 12345")).toBeInTheDocument();
```
#### Interacting with components
@@ -327,7 +317,6 @@ For example, this means that a `click` event from the user would be accompanied
The most convenient events to test are typically `click`, `keyboard` and `pointer` (to simulate touch events).
To dive deeper into these events, you can learn about them in the [`user-event` documentation](https://testing-library.com/docs/user-event/intro).
-
##### Using timers
If you require a fake timer and want to use `vi.useFakeTimers()` in your tests, it must set it up with an `advanceTimers` option:
@@ -363,7 +352,7 @@ describe("pre-login: sign-in", () => {
`vitest` comes with the `expect` function to facilitate assertions that works like:
```tsx frame="none"
-expect(subject)[assertion](value)
+expect(subject)[assertion](value);
```
The command supports assertions like `toBe` (reference comparison) and `toEqual` (value comparison) out of the box.
@@ -376,25 +365,23 @@ For testing inside the DOM, the package `@testing-library/jest-dom` augments it
- [`.toHaveAccessibleDescription(description)`](https://github.com/testing-library/jest-dom?tab=readme-ov-file#tohaveaccessibledescription) - checks accessible description
- and a [lot more](https://github.com/testing-library/jest-dom?tab=readme-ov-file#custom-matchers).
-
### Directive testing
[Directives](/reference/jsx-attributes/use) are reusable behaviors for elements.
They receive the HTML element they are bound to as their first and an accessor of the directive prop as their second argument.
To make testing them more concise, [`@solidjs/testing-library` has a `renderDirective`](https://testing-library.com/docs/solid-testing-library/api#renderdirective) function:
-
```ts frame="none"
const renderResult = renderDirective(directive, {
- initialValue, // value initially added to the argument signal
- targetElement, // opt. node name or element used as target for the directive
- ...renderOptions, // see render options
-})
+ initialValue, // value initially added to the argument signal
+ targetElement, // opt. node name or element used as target for the directive
+ ...renderOptions, // see render options
+});
const {
- arg, // getter for the directive's argument
- setArg, // setter for the directive's argument
- ...renderResults, // see render results
-} = renderResult
+ arg, // getter for the directive's argument
+ setArg, // setter for the directive's argument
+ ...renderResults // see render results
+} = renderResult;
```
In `...renderResults`, the container will contain the `targetElement`, which defaults to a `
@@ -443,32 +432,31 @@ To avoid this, there is a [`renderHook` utility](https://testing-library.com/doc
```ts frame="none"
const renderResult = renderHook(hook, {
- initialProps, // an array with arguments being supplied to the hook
- wrapper, // same as the wrapper optionss for `render`
-})
+ initialProps, // an array with arguments being supplied to the hook
+ wrapper, // same as the wrapper optionss for `render`
+});
const {
- result, // return value of the hook (mutable, destructuring fixes it)
- cleanup, // manually remove the traces of the test from the DOM
- owner, // the owner running the hook to use with `runWithOwner()`
-} = renderResult
+ result, // return value of the hook (mutable, destructuring fixes it)
+ cleanup, // manually remove the traces of the test from the DOM
+ owner, // the owner running the hook to use with `runWithOwner()`
+} = renderResult;
```
A primitive that manages the state of a counter could be tested like this:
```ts frame="none"
-import { test, expect } from "vitest"
-import { renderHook } from "@solidjs/testing-library"
-import { createCounter } from "./counter"
+import { test, expect } from "vitest";
+import { renderHook } from "@solidjs/testing-library";
+import { createCounter } from "./counter";
test("increments count", () => {
- const { result } = renderHook(createCounter)
- expect(result.count).toBe(0)
- result.increment()
- expect(result.count).toBe(1)
-})
+ const { result } = renderHook(createCounter);
+ expect(result.count).toBe(0);
+ result.increment();
+ expect(result.count).toBe(1);
+});
```
-
### Testing effects
Since effects may happen asynchronously, it can be difficult to test them.
@@ -479,19 +467,19 @@ Any errors that would hit the next boundary are used to reject the returned prom
An example test using `testEffect` may look like this:
```ts frame="none"
-const [value, setValue] = createSignal(0)
-return testEffect(done =>
- createEffect((run: number = 0) => {
- if (run === 0) {
- expect(value()).toBe(0)
- setValue(1)
- } else if (run === 1) {
- expect(value()).toBe(1)
- done()
- }
- return run + 1
- })
-)
+const [value, setValue] = createSignal(0);
+return testEffect((done) =>
+ createEffect((run: number = 0) => {
+ if (run === 0) {
+ expect(value()).toBe(0);
+ setValue(1);
+ } else if (run === 1) {
+ expect(value()).toBe(1);
+ done();
+ }
+ return run + 1;
+ })
+);
```
### Benchmarks
@@ -500,40 +488,51 @@ While Solid offers performance simplified, it is good to validate if that promis
Vitest offers an experimental `bench` function to run benchmarks and compare the results inside the same `describe` block;
for example if you had a `` flow component similar to ``, you could benchmark it like this:
-
```jsx title="list.bench.jsx"
-describe('list rendering', () => {
- const ITEMS = 1000
- const renderedFor = new Set()
- const listFor = Array.from({ length: ITEMS }, (_, i) => i)
- bench('For', () => new Promise((resolve) => {
- const ItemFor = (props) => {
- onMount(() => {
- renderedFor.add(props.number)
- if (renderedFor.size === ITEMS) { resolve() }
- })
- return {props.number}
- }
- render(() =>
- {(item) => }
- )
- }))
-
- const renderedList = new Set()
- const listList = Array.from({ length: ITEMS }, (_, i) => i)
- bench('List', () => new Promise((resolve) => {
- const ItemList = (props) => {
- onMount(() => {
- renderedList.add(props.number)
- if (renderedList.size === ITEMS) { resolve() }
- })
- return {props.number}
- }
- render(() =>
- {(item) => }
- )
- }))
-})
+describe("list rendering", () => {
+ const ITEMS = 1000;
+ const renderedFor = new Set();
+ const listFor = Array.from({ length: ITEMS }, (_, i) => i);
+ bench(
+ "For",
+ () =>
+ new Promise((resolve) => {
+ const ItemFor = (props) => {
+ onMount(() => {
+ renderedFor.add(props.number);
+ if (renderedFor.size === ITEMS) {
+ resolve();
+ }
+ });
+ return {props.number};
+ };
+ render(() => (
+ {(item) => }
+ ));
+ })
+ );
+
+ const renderedList = new Set();
+ const listList = Array.from({ length: ITEMS }, (_, i) => i);
+ bench(
+ "List",
+ () =>
+ new Promise((resolve) => {
+ const ItemList = (props) => {
+ onMount(() => {
+ renderedList.add(props.number);
+ if (renderedList.size === ITEMS) {
+ resolve();
+ }
+ });
+ return {props.number};
+ };
+ render(() => (
+ {(item) => }
+ ));
+ })
+ );
+});
```
Running `[npm|pnpm|yarn] test bench` will then execute the benchmark function:
@@ -556,33 +555,19 @@ Running `[npm|pnpm|yarn] test bench` will then execute the benchmark function:
Please keep in mind that it is very difficult to create meaningful benchmarks.
The numbers should always be taken with a grain of salt, but can still indicate performance degradations if compared between versions.
-
### Test coverage
While coverage numbers can be misleading, they are used by many projects as a rough measurement of code quality.
Vitest supports coverage collection. To use it, it needs an extra package:
-
-```bash frame="none"
-npm i -D @vitest/coverage-v8
-```
-
```bash frame="none" pnpm i -D @vitest/coverage-v8 ```
Also, you need to [set up vitest's coverage feature](https://vitest.dev/guide/coverage.html).
-
### Integration/E2E testing
Some issues can only be found once the code is running in the environment it is supposed to run in.
diff --git a/src/routes/quick-start.mdx b/src/routes/quick-start.mdx
index f9df35feb3..9f96bf1f2f 100644
--- a/src/routes/quick-start.mdx
+++ b/src/routes/quick-start.mdx
@@ -32,21 +32,15 @@ npx degit solidjs/templates/js my-app
```bash frame="none"
@@ -216,17 +177,9 @@ npm run dev
```
-
-```bash frame="none"
-yarn dev
-```
-
+
```bash frame="none" yarn dev ```
-
-```bash frame="none"
-pnpm dev
-```
-
+
```bash frame="none" pnpm dev ```
```bash frame="none"
@@ -240,7 +193,6 @@ deno task dev
-
This will start the development server.
Now, you can open your browser and navigate to `localhost:3000` to see your application running.
diff --git a/src/routes/reference/basic-reactivity/create-effect.mdx b/src/routes/reference/basic-reactivity/create-effect.mdx
index d935019670..4b5cb7a483 100644
--- a/src/routes/reference/basic-reactivity/create-effect.mdx
+++ b/src/routes/reference/basic-reactivity/create-effect.mdx
@@ -3,10 +3,9 @@ title: createEffect
---
```tsx
-import { createEffect } from "solid-js"
-
-function createEffect(fn: (v: T) => T, value?: T): void
+import { createEffect } from "solid-js";
+function createEffect(fn: (v: T) => T, value?: T): void;
```
Effects are a general way to make arbitrary code ("side effects") run whenever dependencies change, e.g., to modify the DOM manually.
@@ -15,10 +14,10 @@ Effects are a general way to make arbitrary code ("side effects") run whenever d
For example:
```tsx
-const [a, setA] = createSignal(initialValue)
+const [a, setA] = createSignal(initialValue);
// effect that depends on signal `a`
-createEffect(() => doSideEffect(a()))
+createEffect(() => doSideEffect(a()));
```
The effect will run whenever `a` changes value.
@@ -30,15 +29,15 @@ The effect callback can return a value, which will be passed as the `prev` argum
This is useful for memoizing values that are expensive to compute. For example:
```tsx
-const [a, setA] = createSignal(initialValue)
+const [a, setA] = createSignal(initialValue);
// effect that depends on signal `a`
createEffect((prevSum) => {
// do something with `a` and `prevSum`
- const sum = a() + b()
- if (sum !== prevSum) console.log("sum changed to", sum)
- return sum
-}, 0)
+ const sum = a() + b();
+ if (sum !== prevSum) console.log("sum changed to", sum);
+ return sum;
+}, 0);
// ^ the initial value of the effect is 0
```
@@ -50,21 +49,21 @@ If you want to wait for the first execution to occur, use [queueMicrotask](https
```tsx
// assume this code is in a component function, so is part of a rendering phase
-const [count, setCount] = createSignal(0)
+const [count, setCount] = createSignal(0);
// this effect prints count at the beginning and when it changes
-createEffect(() => console.log("count =", count()))
+createEffect(() => console.log("count =", count()));
// effect won't run yet
-console.log("hello")
-setCount(1) // effect still won't run yet
-setCount(2) // effect still won't run yet
+console.log("hello");
+setCount(1); // effect still won't run yet
+setCount(2); // effect still won't run yet
queueMicrotask(() => {
// now `count = 2` will print
- console.log("microtask")
- setCount(3) // immediately prints `count = 3`
- console.log("goodbye")
-})
+ console.log("microtask");
+ setCount(3); // immediately prints `count = 3`
+ console.log("goodbye");
+});
// --- overall output: ---
// hello
@@ -91,11 +90,11 @@ For example:
```tsx
// listen to event dynamically given by eventName signal
createEffect(() => {
- const event = eventName()
- const callback = (e) => console.log(e)
- ref.addEventListener(event, callback)
- onCleanup(() => ref.removeEventListener(event, callback))
-})
+ const event = eventName();
+ const callback = (e) => console.log(e);
+ ref.addEventListener(event, callback);
+ onCleanup(() => ref.removeEventListener(event, callback));
+});
```
## Arguments
diff --git a/src/routes/reference/basic-reactivity/create-memo.mdx b/src/routes/reference/basic-reactivity/create-memo.mdx
index 58f21b1401..c328704c53 100644
--- a/src/routes/reference/basic-reactivity/create-memo.mdx
+++ b/src/routes/reference/basic-reactivity/create-memo.mdx
@@ -2,36 +2,35 @@
title: createMemo
---
-Memos let you efficiently use a derived value in many reactive computations.
+Memos let you efficiently use a derived value in many reactive computations.
`createMemo` creates a readonly reactive value equal to the return value of the given function and makes sure that function only gets executed when its dependencies change.
```tsx
-import { createMemo } from "solid-js"
+import { createMemo } from "solid-js";
function createMemo(
fn: (v: T) => T,
value?: T,
options?: { equals?: false | ((prev: T, next: T) => boolean) }
-): () => T
-
+): () => T;
```
Here's an example of how createMemo can be used:
```ts
-const value = createMemo(() => computeExpensiveValue(a(), b()))
+const value = createMemo(() => computeExpensiveValue(a(), b()));
//read the value
-value()
+value();
```
-In Solid, you often don't need to wrap functions in memos; you can alternatively just define and call a regular function to get similar reactive behavior.
-The main difference is when you call the function in multiple reactive settings.
-In this case, when the function's dependencies update, the function will get called multiple times unless it is wrapped in createMemo.
+In Solid, you often don't need to wrap functions in memos; you can alternatively just define and call a regular function to get similar reactive behavior.
+The main difference is when you call the function in multiple reactive settings.
+In this case, when the function's dependencies update, the function will get called multiple times unless it is wrapped in createMemo.
For example:
```tsx
-const user = createMemo(() => searchForUser(username()))
+const user = createMemo(() => searchForUser(username()));
// compare with: const user = () => searchForUser(username());
return (
@@ -40,27 +39,27 @@ return (
Your email is {user()?.email}
-)
+);
```
-When the username signal updates, searchForUser will get called just once.
+When the username signal updates, searchForUser will get called just once.
If the returned user actually changed, the user memo updates, and then both list items will update automatically.
If we had instead defined user as a plain function `() => searchForUser(username())`, then `searchForUser` would have been called twice, once when updating each list item.
-Another key difference is that a memo can shield dependents from updating when the memo's dependencies change but the resulting memo value doesn't.
-Like [createSignal](/reference/basic-reactivity/create-signal), the derived signal made by `createMemo` updates (and triggers dependents to rerun) only when the value returned by the memo function actually changes from the previous value, according to JavaScript's `===` operator.
+Another key difference is that a memo can shield dependents from updating when the memo's dependencies change but the resulting memo value doesn't.
+Like [createSignal](/reference/basic-reactivity/create-signal), the derived signal made by `createMemo` updates (and triggers dependents to rerun) only when the value returned by the memo function actually changes from the previous value, according to JavaScript's `===` operator.
Alternatively, you can pass an options object with `equals` set to false to always update the memo when its dependencies change, or you can pass your own `equals` function for testing equality.
-The memo function is called with an argument equal to the value returned from the previous execution of the memo function, or, on the first call, equal to the optional second argument to `createMemo`.
+The memo function is called with an argument equal to the value returned from the previous execution of the memo function, or, on the first call, equal to the optional second argument to `createMemo`.
This is useful for reducing computations, such as:
```tsx
// track the sum of all values taken on by input() as it updates
-const sum = createMemo((prev) => input() + prev, 0)
+const sum = createMemo((prev) => input() + prev, 0);
```
-The memo function should not change other signals by calling setters (it should be "pure").
+The memo function should not change other signals by calling setters (it should be "pure").
This enables Solid to optimize the execution order of memo updates according to their dependency graph, so that all memos can update at most once in response to a dependency change.
## Options and arguments
diff --git a/src/routes/reference/basic-reactivity/create-resource.mdx b/src/routes/reference/basic-reactivity/create-resource.mdx
index e95b4aee91..e8de5b3ebc 100644
--- a/src/routes/reference/basic-reactivity/create-resource.mdx
+++ b/src/routes/reference/basic-reactivity/create-resource.mdx
@@ -4,26 +4,26 @@ title: createResource
`createResource` takes an asynchronous fetcher function and returns a signal that is updated with the resulting data when the fetcher completes.
-There are two ways to use `createResource`: you can pass the fetcher function as the sole argument, or you can additionally pass a source signal as the first argument.
+There are two ways to use `createResource`: you can pass the fetcher function as the sole argument, or you can additionally pass a source signal as the first argument.
The source signal will retrigger the fetcher whenever it changes, and its value will be passed to the fetcher.
```tsx
-const [data, { mutate, refetch }] = createResource(fetchData)
+const [data, { mutate, refetch }] = createResource(fetchData);
```
```tsx
-const [data, { mutate, refetch }] = createResource(source, fetchData)
+const [data, { mutate, refetch }] = createResource(source, fetchData);
```
-In these snippets, the fetcher is the function `fetchData`, and `data()` is undefined until `fetchData` finishes resolving.
-In the first case, `fetchData` will be called immediately.
-In the second, `fetchData` will be called as soon as `source` has any value other than false, null, or undefined.
+In these snippets, the fetcher is the function `fetchData`, and `data()` is undefined until `fetchData` finishes resolving.
+In the first case, `fetchData` will be called immediately.
+In the second, `fetchData` will be called as soon as `source` has any value other than false, null, or undefined.
It will be called again whenever the value of `source` changes, and that value will always be passed to `fetchData` as its first argument.
-You can call `mutate` to directly update the `data` signal (it works like any other signal setter).
+You can call `mutate` to directly update the `data` signal (it works like any other signal setter).
You can also call refetch to rerun the fetcher directly, and pass an optional argument to provide additional info to the fetcher e.g `refetch(info)`.
-`data` works like a normal signal getter: use `data()` to read the last returned value of `fetchData`.
+`data` works like a normal signal getter: use `data()` to read the last returned value of `fetchData`.
But it also has extra reactive properties:
- `data.loading`: whether the fetcher has been called but not returned.
@@ -33,8 +33,8 @@ But it also has extra reactive properties:
- Fetcher throws an `Error` instance, `data.error` will be that instance.
- If the fetcher throws a string, `data.error.message` will contain that string.
- When the fetcher throws a value that is neither an `Error` nor a string, that value will be available as `data.error.cause`.
-
-- As of **v1.4.0**, `data.latest` returns the last value received and will not trigger [Suspense](/reference/components/suspense) or [transitions](#TODO); if no value has been returned yet, `data.latest` will act the same as `data()`.
+
+- As of **v1.4.0**, `data.latest` returns the last value received and will not trigger [Suspense](/reference/components/suspense) or [transitions](#TODO); if no value has been returned yet, `data.latest` will act the same as `data()`.
This can be useful if you want to show the out-of-date data while the new data is loading.
`loading`, `error`, and `latest` are reactive getters and can be tracked.
@@ -42,9 +42,9 @@ But it also has extra reactive properties:
## The fetcher
The `fetcher` is the async function that you provide to `createResource` to actually fetch the data.
-It is passed two arguments: the value of the source signal (if provided), and an info object with two properties: `value` and `refetching`.
-The `value` property tells you the previously fetched value.
-The `refetching` property is true if the `fetcher` was triggered using the refetch function and false otherwise.
+It is passed two arguments: the value of the source signal (if provided), and an info object with two properties: `value` and `refetching`.
+The `value` property tells you the previously fetched value.
+The `refetching` property is true if the `fetcher` was triggered using the refetch function and false otherwise.
If the `refetch` function was called with an argument (`refetch(info)`), refetching is set to that argument.
```tsx
@@ -56,23 +56,22 @@ async function fetchData(source, { value, refetching }) {
// or equal to the optional data passed: `refetch(info)`
}
-const [data, { mutate, refetch }] = createResource(getQuery, fetchData)
+const [data, { mutate, refetch }] = createResource(getQuery, fetchData);
// read value
-data()
+data();
// check if loading
-data.loading
+data.loading;
// check if errored
-data.error
+data.error;
// directly set value without creating promise
-mutate(optimisticValue)
+mutate(optimisticValue);
// refetch the last request explicitly
-refetch()
-
+refetch();
```
## Version 1.4.0 and Later
@@ -83,18 +82,18 @@ If you're using `renderToStream`, you can tell Solid to wait for a resource befo
```tsx
// fetches a user and streams content as soon as possible
-const [user] = createResource(() => params.id, fetchUser)
+const [user] = createResource(() => params.id, fetchUser);
// fetches a user but only streams content after this resource has loaded
const [user] = createResource(() => params.id, fetchUser, {
deferStream: true,
-})
+});
```
#### v1.5.0
-1. We've added a new state field which covers a more detailed view of the Resource state beyond `loading` and `error`.
-You can now check whether a Resource is `unresolved`, `pending`, `ready`, `refreshing`, or `error`.
+1. We've added a new state field which covers a more detailed view of the Resource state beyond `loading` and `error`.
+ You can now check whether a Resource is `unresolved`, `pending`, `ready`, `refreshing`, or `error`.
| State | Value resolved | Loading | Has error |
| ------------ | -------------- | ------- | --------- |
@@ -105,38 +104,38 @@ You can now check whether a Resource is `unresolved`, `pending`, `ready`, `refre
| `error` | No | No | Yes |
2. When server-rendering resources, especially when embedding Solid in other systems that fetch data before rendering, you might want to initialize the resource with this prefetched value instead of fetching again and having the resource serialize it in its own state.
-You can use the new `ssrLoadFrom` option for this.
-Instead of using the default `server` value, you can pass `initial` and the resource will use `initialValue` as if it were the result of the first fetch for both SSR and hydration.
+ You can use the new `ssrLoadFrom` option for this.
+ Instead of using the default `server` value, you can pass `initial` and the resource will use `initialValue` as if it were the result of the first fetch for both SSR and hydration.
```tsx
const [data, { mutate, refetch }] = createResource(() => params.id, fetchUser, {
initialValue: preloadedData,
ssrLoadFrom: "initial",
-})
+});
```
-3. Resources can be set with custom defined storage with the same signature as a Signal by using the storage option.
-For example using a custom reconciling store could be done this way:
+3. Resources can be set with custom defined storage with the same signature as a Signal by using the storage option.
+ For example using a custom reconciling store could be done this way:
```tsx
function createDeepSignal(value: T): Signal {
const [store, setStore] = createStore({
value,
- })
+ });
return [
() => store.value,
(v: T) => {
- const unwrapped = unwrap(store.value)
- typeof v === "function" && (v = v(unwrapped))
- setStore("value", reconcile(v))
- return store.value
+ const unwrapped = unwrap(store.value);
+ typeof v === "function" && (v = v(unwrapped));
+ setStore("value", reconcile(v));
+ return store.value;
},
- ] as Signal
+ ] as Signal;
}
const [resource] = createResource(fetcher, {
storage: createDeepSignal,
-})
+});
```
This option is still experimental and may change in the future.
@@ -159,33 +158,33 @@ The `createResource` function takes an optional third argument, an options objec
The function and type definitions for `createResource` are as follows:
```tsx
-import { createResource } from "solid-js"
-import type { ResourceReturn, ResourceOptions } from "solid-js"
+import { createResource } from "solid-js";
+import type { ResourceReturn, ResourceOptions } from "solid-js";
type ResourceReturn = [
{
- (): T | undefined
- state: "unresolved" | "pending" | "ready" | "refreshing" | "errored"
- loading: boolean
- error: any
- latest: T | undefined
+ (): T | undefined;
+ state: "unresolved" | "pending" | "ready" | "refreshing" | "errored";
+ loading: boolean;
+ error: any;
+ latest: T | undefined;
},
{
- mutate: (v: T | undefined) => T | undefined
- refetch: (info: unknown) => Promise | T
- }
-]
+ mutate: (v: T | undefined) => T | undefined;
+ refetch: (info: unknown) => Promise | T;
+ },
+];
type ResourceOptions = {
- initialValue?: T
- name?: string
- deferStream?: boolean
- ssrLoadFrom?: "initial" | "server"
+ initialValue?: T;
+ name?: string;
+ deferStream?: boolean;
+ ssrLoadFrom?: "initial" | "server";
storage?: (
init: T | undefined
- ) => [Accessor, Setter]
- onHydrated?: (k: S | undefined, info: { value: T | undefined }) => void
-}
+ ) => [Accessor, Setter];
+ onHydrated?: (k: S | undefined, info: { value: T | undefined }) => void;
+};
function createResource(
fetcher: (
@@ -193,7 +192,7 @@ function createResource(
info: { value: T | undefined; refetching: boolean | unknown }
) => T | Promise,
options?: ResourceOptions
-): ResourceReturn
+): ResourceReturn;
function createResource(
source: U | false | null | (() => U | false | null),
@@ -202,6 +201,5 @@ function createResource(
info: { value: T | undefined; refetching: boolean | unknown }
) => T | Promise,
options?: ResourceOptions
-): ResourceReturn
-
+): ResourceReturn;
```
diff --git a/src/routes/reference/basic-reactivity/create-signal.mdx b/src/routes/reference/basic-reactivity/create-signal.mdx
index 475a6092e0..35c2e17d0d 100644
--- a/src/routes/reference/basic-reactivity/create-signal.mdx
+++ b/src/routes/reference/basic-reactivity/create-signal.mdx
@@ -2,27 +2,26 @@
title: createSignal
---
-Signals are the most basic reactive primitive.
+Signals are the most basic reactive primitive.
They track a single value (which can be a value of any type) that changes over time.
```tsx
-import { createSignal } from "solid-js"
+import { createSignal } from "solid-js";
function createSignal(
initialValue: T,
options?: {
- equals?: false | ((prev: T, next: T) => boolean)
- name?: string
- internal?: boolean
+ equals?: false | ((prev: T, next: T) => boolean);
+ name?: string;
+ internal?: boolean;
}
-): [get: () => T, set: (v: T) => T]
+): [get: () => T, set: (v: T) => T];
// available types for return value of createSignal:
-import type { Signal, Accessor, Setter } from "solid-js"
-type Signal = [get: Accessor, set: Setter]
-type Accessor = () => T
-type Setter = (v: T | ((prev?: T) => T)) => T
-
+import type { Signal, Accessor, Setter } from "solid-js";
+type Signal = [get: Accessor, set: Setter];
+type Accessor = () => T;
+type Setter = (v: T | ((prev?: T) => T)) => T;
```
The Signal's value starts out equal to the passed first argument `initialValue` (or undefined if there are no arguments).
@@ -30,52 +29,51 @@ The `createSignal` function returns a pair of functions as a two-element array:
In typical use, you would destructure this array into a named Signal like so:
```tsx
-const [count, setCount] = createSignal(0)
-const [ready, setReady] = createSignal(false)
+const [count, setCount] = createSignal(0);
+const [ready, setReady] = createSignal(false);
```
Calling the getter (e.g., `count()` or `ready()`) returns the current value of the Signal.
Crucial to automatic dependency tracking, calling the getter within a tracking scope causes the calling function to depend on this Signal, so that function will rerun if the Signal gets updated.
-Calling the setter (e.g., `setCount(nextCount)` or `setReady(nextReady)`) sets the Signal's value and updates the Signal (triggering dependents to rerun) if the value actually changed (see details below).
-The setter takes either the new value for the signal or a function that maps the previous value of the signal to a new value as its only argument.
+Calling the setter (e.g., `setCount(nextCount)` or `setReady(nextReady)`) sets the Signal's value and updates the Signal (triggering dependents to rerun) if the value actually changed (see details below).
+The setter takes either the new value for the signal or a function that maps the previous value of the signal to a new value as its only argument.
The updated value is also returned by the setter. As an example:
```tsx
// read signal's current value, and
// depend on signal if in a tracking scope
// (but nonreactive outside of a tracking scope):
-const currentCount = count()
+const currentCount = count();
// or wrap any computation with a function,
// and this function can be used in a tracking scope:
-const doubledCount = () => 2 * count()
+const doubledCount = () => 2 * count();
// or build a tracking scope and depend on signal:
-const countDisplay =
{count()}
+const countDisplay =
{count()}
;
// write signal by providing a value:
-setReady(true)
+setReady(true);
// write signal by providing a function setter:
-const newCount = setCount((prev) => prev + 1)
-
+const newCount = setCount((prev) => prev + 1);
```
:::info
- If you want to store a function in a Signal you must use the function form:
+If you want to store a function in a Signal you must use the function form:
- ```tsx
- setValue(() => myFunction);
- ```
+ ```tsx
+ setValue(() => myFunction);
+ ```
- However, functions are not treated specially as the `initialValue` argument to `createSignal`, so you can pass a
- function initial value as is:
+ However, functions are not treated specially as the `initialValue` argument to `createSignal`, so you can pass a
+ function initial value as is:
- ```tsx
- const [func, setFunc] = createSignal(myFunction);
- ```
+ ```tsx
+ const [func, setFunc] = createSignal(myFunction);
+ ```
:::
@@ -99,7 +97,7 @@ If the function returns false, the Signal's value will be updated and dependents
```tsx
const [count, setCount] = createSignal(0, {
equals: (prev, next) => prev === next,
-})
+});
```
Here are some examples of this option in use:
@@ -108,25 +106,25 @@ Here are some examples of this option in use:
// use { equals: false } to allow modifying object in-place;
// normally this wouldn't be seen as an update because the
// object has the same identity before and after change
-const [object, setObject] = createSignal({ count: 0 }, { equals: false })
+const [object, setObject] = createSignal({ count: 0 }, { equals: false });
setObject((current) => {
- current.count += 1
- current.updated = new Date()
- return current
-})
+ current.count += 1;
+ current.updated = new Date();
+ return current;
+});
// use { equals: false } to create a signal that acts as a trigger without storing a value:
-const [depend, rerun] = createSignal(undefined, { equals: false })
+const [depend, rerun] = createSignal(undefined, { equals: false });
// now calling depend() in a tracking scope
// makes that scope rerun whenever rerun() gets called
// define equality based on string length:
const [myString, setMyString] = createSignal("string", {
equals: (newVal, oldVal) => newVal.length === oldVal.length,
-})
+});
-setMyString("string") // considered equal to the last value and won't cause updates
-setMyString("stranger") // considered different and will cause updates
+setMyString("string"); // considered equal to the last value and won't cause updates
+setMyString("stranger"); // considered different and will cause updates
```
### `name`
@@ -135,7 +133,7 @@ The `name` option can be used to give the Signal a name.
This is useful for debugging. The name will be displayed in the devtools.
```tsx
-const [count, setCount] = createSignal(0, { name: "count" })
+const [count, setCount] = createSignal(0, { name: "count" });
```
### `internal`
@@ -144,5 +142,5 @@ The `internal` option can be used to hide the Signal from the devtools.
This is useful for Signals that are used internally by a component and should not be exposed to the user.
```tsx
-const [count, setCount] = createSignal(0, { internal: true })
+const [count, setCount] = createSignal(0, { internal: true });
```
diff --git a/src/routes/reference/component-apis/children.mdx b/src/routes/reference/component-apis/children.mdx
index 2d001fb0c4..a3b440e3ac 100644
--- a/src/routes/reference/component-apis/children.mdx
+++ b/src/routes/reference/component-apis/children.mdx
@@ -6,60 +6,59 @@ title: children
import { children } from "solid-js";
import type { JSX, ResolvedChildren } from "solid-js";
-function children(fn: () => JSX.Element): () => ResolvedChildren
-
+function children(fn: () => JSX.Element): () => ResolvedChildren;
```
-The `children` helper is used for more complex interactions with props.
-When you're not just passing children to another component using `props.children` once in JSX, you should use `children`.
+The `children` helper is used for more complex interactions with props.
+When you're not just passing children to another component using `props.children` once in JSX, you should use `children`.
Props are normally passed in via a getter for `props.children` in this manner:
```tsx
-const resolved = children(() => props.children)
+const resolved = children(() => props.children);
```
-The return value is a [memo](/reference/basic-reactivity/create-memo) evaluating to the resolved children, which updates whenever the children change.
-Using this memo instead of accessing `props.children` directly has some important advantages in some scenarios.
-The underlying issue is that, when you specify component children via JSX, Solid automatically defines `props.children` as a property getter, so that the children are created (in particular, DOM is created) whenever `props.children` gets accessed.
+The return value is a [memo](/reference/basic-reactivity/create-memo) evaluating to the resolved children, which updates whenever the children change.
+Using this memo instead of accessing `props.children` directly has some important advantages in some scenarios.
+The underlying issue is that, when you specify component children via JSX, Solid automatically defines `props.children` as a property getter, so that the children are created (in particular, DOM is created) whenever `props.children` gets accessed.
Two particular consequences:
-1. If you access `props.children` multiple times, the children (and associated DOM) get created multiple times.
-This is useful if you want the DOM to be duplicated (as DOM nodes can appear in only one parent element), but in many cases it creates redundant DOM nodes.
-If you instead call `resolved()` multiple times, you re-use the same children.
+1. If you access `props.children` multiple times, the children (and associated DOM) get created multiple times.
+ This is useful if you want the DOM to be duplicated (as DOM nodes can appear in only one parent element), but in many cases it creates redundant DOM nodes.
+ If you instead call `resolved()` multiple times, you re-use the same children.
-2. If you access `props.children` outside of a tracking scope (e.g., in an event handler), then you create children that will never be cleaned up.
-If you instead call `resolved()`, you re-use the already resolved children.
-You also guarantee that the children are tracked in the current component, as opposed to another tracking scope such as another component.
+2. If you access `props.children` outside of a tracking scope (e.g., in an event handler), then you create children that will never be cleaned up.
+ If you instead call `resolved()`, you re-use the already resolved children.
+ You also guarantee that the children are tracked in the current component, as opposed to another tracking scope such as another component.
-In addition, the `children` helper "resolves" children by calling argumentless functions and flattening arrays of arrays into an array.
+In addition, the `children` helper "resolves" children by calling argumentless functions and flattening arrays of arrays into an array.
For example, a child specified with JSX like `{signal() * 2}` gets wrapped into a getter function `() => count() * 2` in `props.children`, but gets evaluated to an actual number in resolved, properly depending on a count signal.
-If the given `props.children` is not an array (which occurs when the JSX tag has a single child), then the `children` helper will not normalize it into an array.
-This is useful behavior e.g. when the intention is to pass a single function as a child, which can be detected via `typeof resolved() === 'function'`.
+If the given `props.children` is not an array (which occurs when the JSX tag has a single child), then the `children` helper will not normalize it into an array.
+This is useful behavior e.g. when the intention is to pass a single function as a child, which can be detected via `typeof resolved() === 'function'`.
If you want to normalize to an array, the returned memo has a `toArray` method _(new in 1.5)_.
In most cases, you don't need (and in some cases, don't want) to use the `children` helper if you're just passing `props.children` on to another component or element via JSX:
```tsx
const Wrapper = (props) => {
- return
{props.children}
-}
+ return
{props.children}
;
+};
```
-An important aspect of the `children` helper is that it forces the children to be created and resolved, as it accesses `props.children` immediately.
-This can be undesirable for conditional rendering, e.g., when using the children within a [``](/reference/components/show) component.
+An important aspect of the `children` helper is that it forces the children to be created and resolved, as it accesses `props.children` immediately.
+This can be undesirable for conditional rendering, e.g., when using the children within a [``](/reference/components/show) component.
For example, the following code always evaluates the children:
```tsx
-const resolved = children(() => props.children)
+const resolved = children(() => props.children);
-return {resolved()}
+return {resolved()};
```
-To evaluate the children only when `` would render them, you can push the call to children inside a component or a function within ``, which only evaluates its children when `when` condition is true.
+To evaluate the children only when `` would render them, you can push the call to children inside a component or a function within ``, which only evaluates its children when `when` condition is true.
Another nice workaround is to pass `props.children` to the children helper only when you actually want to evaluate the children:
```tsx
-const resolved = children(() => visible() && props.children)
+const resolved = children(() => visible() && props.children);
```
diff --git a/src/routes/reference/component-apis/create-context.mdx b/src/routes/reference/component-apis/create-context.mdx
index 64a335c2aa..e9a807becb 100644
--- a/src/routes/reference/component-apis/create-context.mdx
+++ b/src/routes/reference/component-apis/create-context.mdx
@@ -3,8 +3,7 @@ title: createContext
order: 5
---
-
-Context provides a form of dependency injection in Solid.
+Context provides a form of dependency injection in Solid.
It is used to save from needing to pass data as props through intermediate components (aka **prop drilling**).
This function creates a new context object that can be used with [useContext](/reference/component-apis/use-context) and offers the Provider control flow.
The default value is used when no Provider is found above in the hierarchy.
@@ -14,10 +13,11 @@ The default value is used when no Provider is found above in the hierarchy.
To avoid reinstatiating a new context when Hot-Module Replacement (HMR) occurs, it is recommended to use `createContext` in its own module (file).
-When using HMR, the context is lost when the module is reloaded. Which will cause an error to be thrown as `useContext` will try to access it while it is still reloading.
+ When using HMR, the context is lost when the module is reloaded. Which will
+ cause an error to be thrown as `useContext` will try to access it while it is
+ still reloading.
-
For example:
```ts title="/context/counter.ts"
@@ -27,12 +27,12 @@ export const INITIAL_COUNT = 0;
const INITIAL_STORE_SETTER = {
increment: () => {},
- decrement: () => {}
+ decrement: () => {},
};
export const CounterContext = createContext([
{ count: INITIAL_COUNT },
- INITIAL_STORE_SETTER
+ INITIAL_STORE_SETTER,
]);
```
@@ -44,7 +44,7 @@ import { CounterContext, INITIAL_COUNT } from "./counter.ts";
export function CounterProvider(props) {
const [value, setValue] = createStore({ count: props.initialCount || INITIAL_COUNT })
-
+
const counter = [
value,
{
@@ -67,36 +67,36 @@ export function CounterProvider(props) {
A few imporant notes on how to pass data through the context API:
-- The value passed to provider is passed to `useContext` as is.
-- Wrapping as a reactive expression will not work.
+- The value passed to provider is passed to `useContext` as is.
+- Wrapping as a reactive expression will not work.
- You should pass in Signals and Stores directly instead of accessing them in the JSX.
To learn how to consume the context, see the [useContext](/reference/component-apis/use-context) documentation and the [Context concepts entry](/concepts/context).
## Default Values
-`createContext()` takes an optional "default value" as an argument.
+`createContext()` takes an optional "default value" as an argument.
If `useContext` is called and there is no corresponding context provider above it in the component hierarchy, then the value passed as `defaultValue` is returned.
-However, if no `defaultValue` was passed, then `undefined` is returned in this case.
+However, if no `defaultValue` was passed, then `undefined` is returned in this case.
Also, `defaultValue` (or `undefined`) is returned if `useContext` is called inside an event callback, as it is then outside of the component hierarchy.
-This has implications for TS.
+This has implications for TS.
If no `defaultValue` is passed, then it is possible that `useContext()` will return `undefined`, and the types reflect this.
-Another (used in the example in the previous section) is provide a default value to `createContext()`.
-In that case, `useContext()` will always return a value, and therefore TS will not complain either.
-The pitfall with this approach is that if you _unintentionally_ use `useContext` outside of a provider, it may not be immediately apparent, because the context is still providing a valid value.
+Another (used in the example in the previous section) is provide a default value to `createContext()`.
+In that case, `useContext()` will always return a value, and therefore TS will not complain either.
+The pitfall with this approach is that if you _unintentionally_ use `useContext` outside of a provider, it may not be immediately apparent, because the context is still providing a valid value.
Therefore, if you expect to always use `useContext` within a provider, it is best to use the error based approach described above.
## Type signature
```ts
interface Context {
- id: symbol
- Provider: (props: { value: T; children: any }) => any
- defaultValue: T
+ id: symbol;
+ Provider: (props: { value: T; children: any }) => any;
+ defaultValue: T;
}
-function createContext(defaultValue?: T): Context
+function createContext(defaultValue?: T): Context;
```
diff --git a/src/routes/reference/component-apis/create-unique-id.mdx b/src/routes/reference/component-apis/create-unique-id.mdx
index 65088f3748..311b98fdd7 100644
--- a/src/routes/reference/component-apis/create-unique-id.mdx
+++ b/src/routes/reference/component-apis/create-unique-id.mdx
@@ -3,16 +3,15 @@ title: createUniqueId
---
```ts
-import { createUniqueId } from "solid-js"
-
-function createUniqueId(): string
+import { createUniqueId } from "solid-js";
+function createUniqueId(): string;
```
A universal id generator that is stable across server/browser.
```ts
-const id = createUniqueId()
+const id = createUniqueId();
```
**Note:** on the server this only works under hydratable components.
diff --git a/src/routes/reference/component-apis/lazy.mdx b/src/routes/reference/component-apis/lazy.mdx
index d6b7144330..af7e5e6695 100644
--- a/src/routes/reference/component-apis/lazy.mdx
+++ b/src/routes/reference/component-apis/lazy.mdx
@@ -3,17 +3,17 @@ title: lazy
---
```ts
-import { lazy } from "solid-js"
-import type { Component } from "solid-js"
+import { lazy } from "solid-js";
+import type { Component } from "solid-js";
function lazy>(
fn: () => Promise<{ default: T }>
-): T & { preload: () => Promise }
+): T & { preload: () => Promise };
```
-Used to lazy load components to allow for code splitting.
-Components are not loaded until rendered.
-Lazy loaded components can be used the same as its statically imported counterpart, receiving props etc.
+Used to lazy load components to allow for code splitting.
+Components are not loaded until rendered.
+Lazy loaded components can be used the same as its statically imported counterpart, receiving props etc.
Lazy components trigger ``
```tsx
@@ -21,5 +21,5 @@ Lazy components trigger ``
const ComponentA = lazy(() => import("./ComponentA"));
// use in JSX
-
+;
```
diff --git a/src/routes/reference/component-apis/use-context.mdx b/src/routes/reference/component-apis/use-context.mdx
index e4eb550686..61638297c8 100644
--- a/src/routes/reference/component-apis/use-context.mdx
+++ b/src/routes/reference/component-apis/use-context.mdx
@@ -6,7 +6,7 @@ Used to grab context within a context provider scope to allow for deep passing o
It's therefore used in conjunction with [`createContext`](/reference/component-apis/create-context) to consume the data from a Provider scope and thus avoid passing data through intermediate components (prop drilling).
```ts
-const [state, { increment, decrement }] = useContext(CounterContext)
+const [state, { increment, decrement }] = useContext(CounterContext);
```
## Recommended usage
@@ -15,13 +15,13 @@ It is often a good idea to wrap `useContext` in a function like so:
```ts title="/context/counter-component.tsx"
function useCounterContext() {
- const context = useContext(CounterContext)
+ const context = useContext(CounterContext);
if (!context) {
- throw new Error("useCounterContext: cannot find a CounterContext")
+ throw new Error("useCounterContext: cannot find a CounterContext");
}
- return context
+ return context;
}
```
@@ -31,8 +31,7 @@ And check the [Context concepts](/concepts/context) for more information on how
## Type signature
```ts
-import { type Context } from "solid-js"
+import { type Context } from "solid-js";
-function useContext(context: Context): T
-
-```
\ No newline at end of file
+function useContext(context: Context): T;
+```
diff --git a/src/routes/reference/components/dynamic.mdx b/src/routes/reference/components/dynamic.mdx
index d219595082..b69cbeab08 100644
--- a/src/routes/reference/components/dynamic.mdx
+++ b/src/routes/reference/components/dynamic.mdx
@@ -6,15 +6,15 @@ order: 5
This component lets you insert an arbitrary Component or tag and passes the props through to it.
```tsx
-import { Dynamic } from "solid-js/web"
-import type { JSX } from "solid-js"
+import { Dynamic } from "solid-js/web";
+import type { JSX } from "solid-js";
function Dynamic(
props: T & {
- children?: any
- component?: Component | string | keyof JSX.IntrinsicElements
+ children?: any;
+ component?: Component | string | keyof JSX.IntrinsicElements;
}
-): () => JSX.Element
+): () => JSX.Element;
```
Here's an example of how you can use it:
diff --git a/src/routes/reference/components/for.mdx b/src/routes/reference/components/for.mdx
index a02434702c..7629987fbb 100644
--- a/src/routes/reference/components/for.mdx
+++ b/src/routes/reference/components/for.mdx
@@ -6,14 +6,14 @@ order: 5
The `` component is used to render a list of items. It is similar to the `.map()` function in JavaScript.
```ts
-import { For } from "solid-js"
-import type { JSX } from "solid-js"
+import { For } from "solid-js";
+import type { JSX } from "solid-js";
function For(props: {
- each: readonly T[]
- fallback?: JSX.Element
- children: (item: T, index: () => number) => U
-}): () => U[]
+ each: readonly T[];
+ fallback?: JSX.Element;
+ children: (item: T, index: () => number) => U;
+}): () => U[];
```
A referentially keyed loop with efficient updating of only changed items. The callback takes the current item as the first argument:
diff --git a/src/routes/reference/components/index-component.mdx b/src/routes/reference/components/index-component.mdx
index f3f6b6427f..5eac1d0e82 100644
--- a/src/routes/reference/components/index-component.mdx
+++ b/src/routes/reference/components/index-component.mdx
@@ -5,13 +5,13 @@ title:
Non-keyed list iteration (rendered nodes are keyed to an array index). This is useful when there is no conceptual key, like if the data consists of primitives and it is the index that is fixed rather than the value.
```ts
-import { Index } from "solid-js"
-import type { JSX } from "solid-js"
+import { Index } from "solid-js";
+import type { JSX } from "solid-js";
function Index(props: {
- each: readonly T[];
- fallback?: JSX.Element;
- children: (item: () => T, index: number) => U;
+ each: readonly T[];
+ fallback?: JSX.Element;
+ children: (item: () => T, index: number) => U;
}): () => U[];
```
@@ -19,14 +19,14 @@ A super simple implementation of this component might look like this:
```tsx
function Index(props: {
- each: readonly T[];
- fallback?: JSX.Element;
- children: (item: () => T, index: number) => U;
+ each: readonly T[];
+ fallback?: JSX.Element;
+ children: (item: () => T, index: number) => U;
}) {
- return () => {
- const [items, setItems] = createSignal(props.each);
- return props.each.map((_, i) => props.children(() => items()[i], i));
- };
+ return () => {
+ const [items, setItems] = createSignal(props.each);
+ return props.each.map((_, i) => props.children(() => items()[i], i));
+ };
}
```
@@ -34,7 +34,7 @@ Here's a look at the implementation of the `Index` component in Solid:
```tsx
Loading...}>
- {(item) =>
{item()}
}
+ {(item) =>
{item()}
}
```
@@ -44,11 +44,11 @@ Optional second argument is an index number:
```tsx
Loading...}>
- {(item, index) => (
-
- #{index} {item()}
-
- )}
+ {(item, index) => (
+
+ #{index} {item()}
+
+ )}
```
@@ -58,4 +58,4 @@ Optional second argument is an index number:
| :------- | :------------------------------------ | :-------------------------------------------------------------- |
| each | `readonly T[]` | The array to iterate over. |
| fallback | `JSX.Element` | Optional fallback element to render while the array is loading. |
-| children | `(item: () => T, index: number) => U` | The function that renders the children. |
\ No newline at end of file
+| children | `(item: () => T, index: number) => U` | The function that renders the children. |
diff --git a/src/routes/reference/components/portal.mdx b/src/routes/reference/components/portal.mdx
index 1e49844309..2c0f0b7162 100644
--- a/src/routes/reference/components/portal.mdx
+++ b/src/routes/reference/components/portal.mdx
@@ -7,22 +7,22 @@ title:
This is useful when your UI has some elements that need to appear on top of everything else, such as modals and tooltips.
```tsx
-import { Portal } from "solid-js/web"
-import type { JSX } from "solid-js"
+import { Portal } from "solid-js/web";
+import type { JSX } from "solid-js";
function Portal(props: {
- mount?: Node
- useShadow?: boolean
- isSVG?: boolean
- children: JSX.Element
-}): Text
+ mount?: Node;
+ useShadow?: boolean;
+ isSVG?: boolean;
+ children: JSX.Element;
+}): Text;
```
-This inserts the element in the mount node.
-Useful for inserting Modals outside of the page layout.
+This inserts the element in the mount node.
+Useful for inserting Modals outside of the page layout.
Events still propagate through the component hierarchy, however `` will only run on the client and has hydration _disabled_.
-The portal is mounted in a `
` unless the target is the document head.
+The portal is mounted in a `
` unless the target is the document head.
`useShadow` places the element in a Shadow Root for style isolation, and `isSVG` is required if inserting into an SVG element so that the `
` is not inserted.
```tsx
diff --git a/src/routes/reference/components/show.mdx b/src/routes/reference/components/show.mdx
index b8c1d6f30a..6470ca0596 100644
--- a/src/routes/reference/components/show.mdx
+++ b/src/routes/reference/components/show.mdx
@@ -6,15 +6,15 @@ order: 5
The `Show` control flow is used to conditionally render part of the view: it renders children when `when` is truthy, a fallback otherwise. It is similar to the ternary operator `(when ? children : fallback)` but is ideal for templating JSX.
```ts
-import { Show } from "solid-js"
-import type { JSX } from "solid-js"
+import { Show } from "solid-js";
+import type { JSX } from "solid-js";
function Show(props: {
- when: T | undefined | null | false
- keyed?: boolean
- fallback?: JSX.Element
- children: JSX.Element | ((item: T | Accessor) => JSX.Element)
-}): () => JSX.Element
+ when: T | undefined | null | false;
+ keyed?: boolean;
+ fallback?: JSX.Element;
+ children: JSX.Element | ((item: T | Accessor) => JSX.Element);
+}): () => JSX.Element;
```
Here's an example of using the `Show` control flow:
@@ -43,8 +43,8 @@ If the `keyed` property is not used, the argument of the child function will be
## Props
-| Name | Type | Description |
-| :--------- | :-------------------------------- | :-------------------------------------------- |
-| `when` | `T \| undefined \| null \| false` | The value to test for truthiness |
-| `keyed` | `boolean` | Whether to key the block to the value of when |
-| `fallback` | `JSX.Element` | The fallback to render when the `when` is falsy |
+| Name | Type | Description |
+| :--------- | :-------------------------------- | :---------------------------------------------- |
+| `when` | `T \| undefined \| null \| false` | The value to test for truthiness |
+| `keyed` | `boolean` | Whether to key the block to the value of when |
+| `fallback` | `JSX.Element` | The fallback to render when the `when` is falsy |
diff --git a/src/routes/reference/components/suspense-list.mdx b/src/routes/reference/components/suspense-list.mdx
index 38bc42b37b..dac45644e8 100644
--- a/src/routes/reference/components/suspense-list.mdx
+++ b/src/routes/reference/components/suspense-list.mdx
@@ -6,14 +6,14 @@ order: 5
SuspenseList allows for coordinating multiple parallel Suspense and SuspenseList components. It controls the order in which content is revealed to reduce layout thrashing and has an option to collapse or hide fallback states.
```ts
-import { SuspenseList } from "solid-js"
-import type { JSX } from "solid-js"
+import { SuspenseList } from "solid-js";
+import type { JSX } from "solid-js";
function SuspenseList(props: {
- children: JSX.Element
- revealOrder: "forwards" | "backwards" | "together"
- tail?: "collapsed" | "hidden"
-}): JSX.Element
+ children: JSX.Element;
+ revealOrder: "forwards" | "backwards" | "together";
+ tail?: "collapsed" | "hidden";
+}): JSX.Element;
```
**Note**: SuspenseList is still in the experimental stage and does not have full `SSR` support.
diff --git a/src/routes/reference/components/suspense.mdx b/src/routes/reference/components/suspense.mdx
index 07617e081a..39aa9aeba5 100644
--- a/src/routes/reference/components/suspense.mdx
+++ b/src/routes/reference/components/suspense.mdx
@@ -6,14 +6,13 @@ order: 5
A component that tracks all resources read under it and shows a fallback placeholder state until they are resolved. What makes `Suspense` different than `Show` is that it is non-blocking in the sense that both branches exist at the same time even if not currently in the DOM. This means that the fallback can be rendered while the children are loading. This is useful for loading states and other asynchronous operations.
```tsx
-import { Suspense } from "solid-js"
-import type { JSX } from "solid-js"
+import { Suspense } from "solid-js";
+import type { JSX } from "solid-js";
function Suspense(props: {
- fallback?: JSX.Element
- children: JSX.Element
-}): JSX.Element
-
+ fallback?: JSX.Element;
+ children: JSX.Element;
+}): JSX.Element;
```
Here's an example of a `Suspense` component that shows a loading spinner while the `User` component is loading.
@@ -22,7 +21,6 @@ Here's an example of a `Suspense` component that shows a loading spinner while t
}>
-
```
## Nested Suspense
@@ -60,15 +58,14 @@ Our example use case is to display a user profile. A naive snippet would look li
const MyComponentWithOptionalChaining = () => {
const [profile] = createResource(async () => {
/* fetcher code here */
- })
+ });
return (
<>
{profile()?.name}
{profile()?.email}
>
- )
-}
-
+ );
+};
```
In this code, `profile()` starts as `undefined`, and when the fetcher code finishes, resolves to an object with `name` and `email` properties. Although the resource has not resolved yet, the two `div`s are already created and attached to the document body, albeit with empty text nodes. Once the resource resolves, the `div`s are updated with the appropriate data.
@@ -79,15 +76,14 @@ The downside of this approach is that the user is shown an empty component - let
const MyComponentWithShow = () => {
const [profile] = createResource(async () => {
/* fetcher code here */
- })
+ });
return (
fetching user data
}>
{profile().name}
{profile().email}
- )
-}
-
+ );
+};
```
In this snippet, we first show a fallback when the resource hasn't resolved yet, and then switch to showing the profile data once it has. This results in a better user experience.
@@ -100,14 +96,14 @@ We can have the best of both worlds by using {""}:
const MyComponentWithSuspense = () => {
const [profile] = createResource(async () => {
/* fetcher code here */
- })
+ });
return (
fetching user data
}>
{profile()?.name}
{profile()?.email}
- )
-}
+ );
+};
```
In this case, the `div`s are created immediately, but instead of being attached to the document body, the fallback is shown. Once the resource resolves, the text in the `div`s is updated, and then they are attached to the document (and the fallback removed).
@@ -120,7 +116,7 @@ With this in mind, we can understand that there isn't much gained from suspense
const MyComponentWithSuspenseAndShow = () => {
const [profile] = createResource(async () => {
/* fetcher code here */
- })
+ });
return (
fetching user data
- )
-}
+ );
+};
```
In this code, we don't create _any_ DOM nodes inside {""} before the resource resolves, so it is pretty much the same as the second example where we only used ``.
:::info
- Suspense is triggered by reading a resource inside the {""}{" "}
- boundary. Components wrapped with suspense still run fully, just as they would
- without suspense. However, code wrapped in `onMount` and `createEffect` only
- run after the resource resolves.
+Suspense is triggered by reading a resource inside the {""}{" "}
+boundary. Components wrapped with suspense still run fully, just as they would
+without suspense. However, code wrapped in `onMount` and `createEffect` only
+run after the resource resolves.
:::
## Props
diff --git a/src/routes/reference/components/switch-and-match.mdx b/src/routes/reference/components/switch-and-match.mdx
index f733467b5b..d7c2c03565 100644
--- a/src/routes/reference/components/switch-and-match.mdx
+++ b/src/routes/reference/components/switch-and-match.mdx
@@ -6,35 +6,35 @@ order: 5
Useful for when there are more than 2 mutual exclusive conditions. It is a more flexible version of the if-else-if-else-if-else-... chain.
```ts
-import { Switch, Match } from "solid-js"
-import type { MatchProps, JSX } from "solid-js"
+import { Switch, Match } from "solid-js";
+import type { MatchProps, JSX } from "solid-js";
function Switch(props: {
- fallback?: JSX.Element
- children: JSX.Element
-}): () => JSX.Element
+ fallback?: JSX.Element;
+ children: JSX.Element;
+}): () => JSX.Element;
type MatchProps = {
- when: T | undefined | null | false
- children: JSX.Element | ((item: T) => JSX.Element)
-}
-function Match(props: MatchProps)
+ when: T | undefined | null | false;
+ children: JSX.Element | ((item: T) => JSX.Element);
+};
+function Match(props: MatchProps);
```
A super simple implementation of this component would be:
```tsx
function Switch(props) {
- let children = props.children
+ let children = props.children;
- if (!Array.isArray(children)) children = [children]
+ if (!Array.isArray(children)) children = [children];
for (let i = 0; i < children.length; i++) {
- const child = children[i]
- if (child.props.when) return child
+ const child = children[i];
+ if (child.props.when) return child;
}
- return props.fallback
+ return props.fallback;
}
```
diff --git a/src/routes/reference/jsx-attributes/attr.mdx b/src/routes/reference/jsx-attributes/attr.mdx
index 4faaed5138..7e8540dacc 100644
--- a/src/routes/reference/jsx-attributes/attr.mdx
+++ b/src/routes/reference/jsx-attributes/attr.mdx
@@ -10,6 +10,7 @@ Useful for Web Components where you want to set attributes.
```
- Type definitions are required when using TypeScript.
- See the[TypeScript](/configuration/typescript#forcing-properties-and-custom-attributes) page for examples.
+ Type definitions are required when using TypeScript. See
+ the[TypeScript](/configuration/typescript#forcing-properties-and-custom-attributes)
+ page for examples.
diff --git a/src/routes/reference/jsx-attributes/bool.mdx b/src/routes/reference/jsx-attributes/bool.mdx
index b881e77e9c..3e7373e2ac 100644
--- a/src/routes/reference/jsx-attributes/bool.mdx
+++ b/src/routes/reference/jsx-attributes/bool.mdx
@@ -21,6 +21,7 @@ This attribute is most useful for Web Components.
```
- Type definitions are required when using TypeScript.
- See the [TypeScript](/configuration/typescript#forcing-properties-and-custom-attributes) page for examples.
+ Type definitions are required when using TypeScript. See the
+ [TypeScript](/configuration/typescript#forcing-properties-and-custom-attributes)
+ page for examples.
diff --git a/src/routes/reference/jsx-attributes/classlist.mdx b/src/routes/reference/jsx-attributes/classlist.mdx
index 69f2f39089..09ce8d3a3b 100644
--- a/src/routes/reference/jsx-attributes/classlist.mdx
+++ b/src/routes/reference/jsx-attributes/classlist.mdx
@@ -19,9 +19,9 @@ First, you can set class=... like any other attribute. For example:
```
:::info
- Note that className was deprecated in Solid 1.4 in favor of{" "}
- class.
-:::
+Note that className was deprecated in Solid 1.4 in favor of{" "}
+
+class. :::
Alternatively, the `classList` pseudo-attribute lets you specify an object, where each key is a class and the value is treated as a boolean representing whether to include that class. For example (matching the last example):
diff --git a/src/routes/reference/jsx-attributes/on.mdx b/src/routes/reference/jsx-attributes/on.mdx
index 3f81b85097..1b1a6c6bd7 100644
--- a/src/routes/reference/jsx-attributes/on.mdx
+++ b/src/routes/reference/jsx-attributes/on.mdx
@@ -12,6 +12,7 @@ For events with capital letters, listener options, or if you need to attach even
This directly attaches an event handler (via [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)) to the `div`.
:::info
+
New in v1.9.0
:::
diff --git a/src/routes/reference/jsx-attributes/prop.mdx b/src/routes/reference/jsx-attributes/prop.mdx
index a13c553e0c..8a4c7bcb99 100644
--- a/src/routes/reference/jsx-attributes/prop.mdx
+++ b/src/routes/reference/jsx-attributes/prop.mdx
@@ -10,6 +10,7 @@ Forces the prop to be treated as a property instead of an attribute.
```
- Type definitions are required when using TypeScript.
- See the [TypeScript](/configuration/typescript#forcing-properties-and-custom-attributes) page for examples.
-
\ No newline at end of file
+ Type definitions are required when using TypeScript. See the
+ [TypeScript](/configuration/typescript#forcing-properties-and-custom-attributes)
+ page for examples.
+
diff --git a/src/routes/reference/jsx-attributes/ref.mdx b/src/routes/reference/jsx-attributes/ref.mdx
index 630806570f..1f62335a02 100644
--- a/src/routes/reference/jsx-attributes/ref.mdx
+++ b/src/routes/reference/jsx-attributes/ref.mdx
@@ -22,12 +22,12 @@ Refs can also be used on Components. They still need to be attached on the other
```tsx
function MyComp(props) {
- return
+ return ;
}
function App() {
- let myDiv
- onMount(() => console.log(myDiv.clientWidth))
- return
+ let myDiv;
+ onMount(() => console.log(myDiv.clientWidth));
+ return ;
}
```
diff --git a/src/routes/reference/jsx-attributes/use.mdx b/src/routes/reference/jsx-attributes/use.mdx
index cce2a68272..9849e5ff97 100644
--- a/src/routes/reference/jsx-attributes/use.mdx
+++ b/src/routes/reference/jsx-attributes/use.mdx
@@ -6,21 +6,21 @@ order: 5
These are custom directives. In a sense this is just syntax sugar over ref but allows us to easily attach multiple directives to a single element. A directive is a function with the following signature:
```ts
-function directive(element: Element, accessor: () => any): void
+function directive(element: Element, accessor: () => any): void;
```
Directive functions are called at render time but before being added to the DOM. You can do whatever you'd like in them including create signals, effects, register clean-up etc.
```tsx
-const [name, setName] = createSignal("")
+const [name, setName] = createSignal("");
function model(el, value) {
- const [field, setField] = value()
- createRenderEffect(() => (el.value = field()))
- el.addEventListener("input", (e) => setField(e.target.value))
-};
+ const [field, setField] = value();
+ createRenderEffect(() => (el.value = field()));
+ el.addEventListener("input", (e) => setField(e.target.value));
+}
-
+;
```
To register with TypeScript extend the JSX namespace.
@@ -29,7 +29,7 @@ To register with TypeScript extend the JSX namespace.
declare module "solid-js" {
namespace JSX {
interface Directives {
- model: [() => any, (v: any) => any]
+ model: [() => any, (v: any) => any];
}
}
}
diff --git a/src/routes/reference/lifecycle/on-cleanup.mdx b/src/routes/reference/lifecycle/on-cleanup.mdx
index 43a4640238..e31125cc92 100644
--- a/src/routes/reference/lifecycle/on-cleanup.mdx
+++ b/src/routes/reference/lifecycle/on-cleanup.mdx
@@ -10,7 +10,7 @@ When used in a Component, it runs when the component is unmounted.
When used in reactive contexts, such [`createEffect`](/reference/basic-reactivity/create-effect), [`createMemo`](/reference/basic-reactivity/create-memo) or a [`createRoot`](/reference/reactive-utilities/create-root), it runs when the reactive scope is disposed or refreshed.
```ts
-import { onCleanup } from "solid-js"
+import { onCleanup } from "solid-js";
function onCleanup(fn: () => void): void;
```
@@ -19,7 +19,7 @@ Without the `onCleanup` function, the event listener would remain attached to th
This can cause memory leaks and other issues.
```tsx
-import { createSignal, onCleanup } from "solid-js"
+import { createSignal, onCleanup } from "solid-js";
const Component = () => {
const [count, setCount] = createSignal(0);
diff --git a/src/routes/reference/lifecycle/on-mount.mdx b/src/routes/reference/lifecycle/on-mount.mdx
index 9d59843dd4..5afd8e7f80 100644
--- a/src/routes/reference/lifecycle/on-mount.mdx
+++ b/src/routes/reference/lifecycle/on-mount.mdx
@@ -7,25 +7,24 @@ Registers a method that runs after initial rendering is done and the elements ar
Ideal for using [refs](/reference/jsx-attributes/ref) and managing other one-time setup.
```tsx
-import { onMount } from "solid-js"
-
-function onMount(fn: () => void): void
+import { onMount } from "solid-js";
+function onMount(fn: () => void): void;
```
This is an alias for an effect that is non-tracking, meaning that it is equivalent to a [`createEffect`](/reference/basic-reactivity/create-effect) with no dependencies.
```tsx
// example that shows how to use onMount to get a reference to an element
-import { onMount } from "solid-js"
+import { onMount } from "solid-js";
function MyComponent() {
- let ref: HTMLButtonElement
+ let ref: HTMLButtonElement;
// when the component is mounted, the button will be disabled
onMount(() => {
- ref.disabled = true
- })
- return Focus me!
+ ref.disabled = true;
+ });
+ return Focus me!;
}
```
diff --git a/src/routes/reference/reactive-utilities/batch.mdx b/src/routes/reference/reactive-utilities/batch.mdx
index 1763c98198..04b5a0bf14 100644
--- a/src/routes/reference/reactive-utilities/batch.mdx
+++ b/src/routes/reference/reactive-utilities/batch.mdx
@@ -3,9 +3,9 @@ title: batch
---
```ts
-import { batch } from "solid-js"
+import { batch } from "solid-js";
-function batch(fn: () => T): T
+function batch(fn: () => T): T;
```
`batch` is a low-level API that batches updates together.
@@ -16,44 +16,44 @@ Batching improves performance by avoiding unnecessary recalculation.
Suppose you have a downstream memo `down` that depends on multiple upstream signals `up1`, `up2`, and `up3`:
```ts
-import { createSignal, createMemo, createEffect } from "solid-js"
-const [up1, setUp1] = createSignal(1)
-const [up2, setUp2] = createSignal(2)
-const [up3, setUp3] = createSignal(3)
-const down = createMemo(() => up1() + up2() + up3())
+import { createSignal, createMemo, createEffect } from "solid-js";
+const [up1, setUp1] = createSignal(1);
+const [up2, setUp2] = createSignal(2);
+const [up3, setUp3] = createSignal(3);
+const down = createMemo(() => up1() + up2() + up3());
// For illustration, monitor when `down` gets recomputed:
-createEffect(() => console.log(down())) // outputs 6
+createEffect(() => console.log(down())); // outputs 6
```
If you directly update all of the upstream signals outside of batch mode, then `down` will recompute every time.
```ts
-setUp1(4) // recomputes down, outputs 9
-setUp2(5) // recomputes down, outputs 12
-setUp3(6) // recomputes down, outputs 15
+setUp1(4); // recomputes down, outputs 9
+setUp2(5); // recomputes down, outputs 12
+setUp3(6); // recomputes down, outputs 15
```
If instead you update the upstream signals within a `batch`, then `down` will update only once at the end:
```ts
batch(() => {
- setUp1(10) // doesn't update down yet
- setUp2(10) // doesn't update down yet
- setUp3(10) // doesn't update down yet
-}) // recomputes down, outputs 30
+ setUp1(10); // doesn't update down yet
+ setUp2(10); // doesn't update down yet
+ setUp3(10); // doesn't update down yet
+}); // recomputes down, outputs 30
```
-The impact is even more dramatic if you have *m* downstream computations (memos, effects, etc.) that each depends on *n* upstream signals.
-Without batching, modifying all *n* upstream signals would cause *m n* updates to the downstream computations.
-With batching, modifying all *n* upstream signals would cause *m* updates to the downstream computations.
-Given that each update takes at least *n* time (just to read the upstream signals), this cost savings can be significant.
+The impact is even more dramatic if you have _m_ downstream computations (memos, effects, etc.) that each depends on _n_ upstream signals.
+Without batching, modifying all _n_ upstream signals would cause _m n_ updates to the downstream computations.
+With batching, modifying all _n_ upstream signals would cause _m_ updates to the downstream computations.
+Given that each update takes at least _n_ time (just to read the upstream signals), this cost savings can be significant.
Batching is also especially helpful when the downstream effects include DOM updates, which can be expensive.
Solid uses `batch` internally to automatically batch updates for you in a few cases:
-* Within [`createEffect`](/reference/basic-reactivity/create-effect) and [`onMount`](/reference/lifecycle/on-mount) (unless they are outside a [root](/reference/reactive-utilities/create-root))
-* Within the [setter of a store](/reference/store-utilities/create-store#setter) (which can update several properties at once)
-* Within array methods (e.g. `Array.prototype.splice`) of a [mutable store](/reference/store-utilities/create-mutable) (which can update several elements at once)
+- Within [`createEffect`](/reference/basic-reactivity/create-effect) and [`onMount`](/reference/lifecycle/on-mount) (unless they are outside a [root](/reference/reactive-utilities/create-root))
+- Within the [setter of a store](/reference/store-utilities/create-store#setter) (which can update several properties at once)
+- Within array methods (e.g. `Array.prototype.splice`) of a [mutable store](/reference/store-utilities/create-mutable) (which can update several elements at once)
These save you from having to use `batch` yourself in many cases.
For the most part, automatic batching should be transparent to you, because accessing a signal or memo will cause it to update if it is out of date (as of Solid 1.4).
@@ -61,14 +61,14 @@ For example:
```ts
batch(() => {
- setUp1(11) // doesn't update down yet
- setUp2(11) // doesn't update down yet
- setUp3(11) // doesn't update down yet
- console.log(down()) // recomputes down, outputs 33
- setUp1(12) // doesn't update down yet
- setUp2(12) // doesn't update down yet
- setUp3(12) // doesn't update down yet
-}) // recomputes down, outputs 36
+ setUp1(11); // doesn't update down yet
+ setUp2(11); // doesn't update down yet
+ setUp3(11); // doesn't update down yet
+ console.log(down()); // recomputes down, outputs 33
+ setUp1(12); // doesn't update down yet
+ setUp2(12); // doesn't update down yet
+ setUp3(12); // doesn't update down yet
+}); // recomputes down, outputs 36
```
You can think of `batch(fn)` as setting a global "batch mode" variable, calling the function `fn`, and then restoring the global variable to its previous value.
diff --git a/src/routes/reference/reactive-utilities/catch-error.mdx b/src/routes/reference/reactive-utilities/catch-error.mdx
index bb1df0372c..b4fac787b4 100644
--- a/src/routes/reference/reactive-utilities/catch-error.mdx
+++ b/src/routes/reference/reactive-utilities/catch-error.mdx
@@ -3,13 +3,14 @@ title: catchError
---
:::info
+
New in v1.7.0
:::
```tsx
-import { catchError } from "solid-js"
+import { catchError } from "solid-js";
-function catchError(tryFn: () => T, onError: (err: any) => void): T
+function catchError(tryFn: () => T, onError: (err: any) => void): T;
```
Wraps a `tryFn` with an error handler that fires if an error occurs below that point.
diff --git a/src/routes/reference/reactive-utilities/create-root.mdx b/src/routes/reference/reactive-utilities/create-root.mdx
index aab8ce89ec..46d2454f50 100644
--- a/src/routes/reference/reactive-utilities/create-root.mdx
+++ b/src/routes/reference/reactive-utilities/create-root.mdx
@@ -3,14 +3,13 @@ title: createRoot
---
```ts
-import { createRoot } from "solid-js"
-
-function createRoot(fn: (dispose: () => void) => T): T
+import { createRoot } from "solid-js";
+function createRoot(fn: (dispose: () => void) => T): T;
```
-Creates a new non-tracked owner scope that doesn't auto-dispose.
+Creates a new non-tracked owner scope that doesn't auto-dispose.
This is useful for nested reactive scopes that you do not wish to release when the parent re-evaluates.
-All Solid code should be wrapped in one of these top level as they ensure that all memory/computations are freed up.
+All Solid code should be wrapped in one of these top level as they ensure that all memory/computations are freed up.
Normally you do not need to worry about this as createRoot is embedded into all render entry functions.
diff --git a/src/routes/reference/reactive-utilities/from.mdx b/src/routes/reference/reactive-utilities/from.mdx
index ad45aea13a..f06a48f514 100644
--- a/src/routes/reference/reactive-utilities/from.mdx
+++ b/src/routes/reference/reactive-utilities/from.mdx
@@ -3,7 +3,7 @@ title: from
---
```tsx
-import { from } from "solid-js"
+import { from } from "solid-js";
function from(
producer:
@@ -11,17 +11,16 @@ function from(
| {
subscribe: (
fn: (v: T) => void
- ) => (() => void) | { unsubscribe: () => void }
+ ) => (() => void) | { unsubscribe: () => void };
}
-): () => T | undefined
-
+): () => T | undefined;
```
-A helper to make it easier to interop with external producers like RxJS observables or with Svelte Stores.
+A helper to make it easier to interop with external producers like RxJS observables or with Svelte Stores.
This basically turns any subscribable (object with a subscribe method) into a Signal and manages subscription and disposal.
```tsx
-const signal = from(obsv$)
+const signal = from(obsv$);
```
It can also take a custom producer function where the function is passed a setter function that returns an unsubscribe function:
@@ -29,11 +28,11 @@ It can also take a custom producer function where the function is passed a sette
```tsx
const clock = from((set) => {
const interval = setInterval(() => {
- set((v) => v + 1)
- }, 1000)
+ set((v) => v + 1);
+ }, 1000);
- return () => clearInterval(interval)
-})
+ return () => clearInterval(interval);
+});
```
## Arguments
diff --git a/src/routes/reference/reactive-utilities/get-owner.mdx b/src/routes/reference/reactive-utilities/get-owner.mdx
index 1be5c3f788..60d47672d5 100644
--- a/src/routes/reference/reactive-utilities/get-owner.mdx
+++ b/src/routes/reference/reactive-utilities/get-owner.mdx
@@ -3,22 +3,21 @@ title: getOwner
---
```tsx
-import { getOwner } from "solid-js"
-import type { Owner } from "solid-js"
-
-function getOwner(): Owner
+import { getOwner } from "solid-js";
+import type { Owner } from "solid-js";
+function getOwner(): Owner;
```
Gets the reactive scope that owns the currently running code, e.g., for passing into a later call to `runWithOwner` outside of the current scope.
-Internally, computations (effects, memos, etc.) create owners which are children of their owner, all the way up to the root owner created by `createRoot` or `render`.
-In particular, this ownership tree lets Solid automatically clean up a disposed computation by traversing its subtree and calling all `onCleanup` callbacks.
-For example, when a createEffect's dependencies change, the effect calls all descendant `onCleanup` callbacks before running the effect function again.
+Internally, computations (effects, memos, etc.) create owners which are children of their owner, all the way up to the root owner created by `createRoot` or `render`.
+In particular, this ownership tree lets Solid automatically clean up a disposed computation by traversing its subtree and calling all `onCleanup` callbacks.
+For example, when a createEffect's dependencies change, the effect calls all descendant `onCleanup` callbacks before running the effect function again.
Calling `getOwner` returns the current owner node that is responsible for disposal of the current execution block.
-Components are not computations, so do not create an owner node, but they are typically rendered from a `createEffect` which does, so the result is similar: when a component gets unmounted, all descendant `onCleanup` callbacks get called.
+Components are not computations, so do not create an owner node, but they are typically rendered from a `createEffect` which does, so the result is similar: when a component gets unmounted, all descendant `onCleanup` callbacks get called.
Calling `getOwner` from a component scope returns the owner that is responsible for rendering and unmounting that component.
-Note that the owning reactive scope isn't necessarily tracking.
+Note that the owning reactive scope isn't necessarily tracking.
For example, untrack turns off tracking for the duration of a function (without creating a new reactive scope), as do components created via JSX (``).
diff --git a/src/routes/reference/reactive-utilities/index-array.mdx b/src/routes/reference/reactive-utilities/index-array.mdx
index a8b6036eef..45fd936d77 100644
--- a/src/routes/reference/reactive-utilities/index-array.mdx
+++ b/src/routes/reference/reactive-utilities/index-array.mdx
@@ -3,16 +3,15 @@ title: indexArray
---
```tsx
-import { indexArray } from "solid-js"
+import { indexArray } from "solid-js";
function indexArray(
list: () => readonly T[],
mapFn: (v: () => T, i: number) => U
-): () => U[]
-
+): () => U[];
```
-Similar to `mapArray` except it maps by index.
+Similar to `mapArray` except it maps by index.
The item is a signal and the index is now the constant.
Underlying helper for the `` control flow.
diff --git a/src/routes/reference/reactive-utilities/map-array.mdx b/src/routes/reference/reactive-utilities/map-array.mdx
index 78e2dbfd4a..8bb41e7135 100644
--- a/src/routes/reference/reactive-utilities/map-array.mdx
+++ b/src/routes/reference/reactive-utilities/map-array.mdx
@@ -3,38 +3,37 @@ title: mapArray
---
```ts
-import { mapArray } from "solid-js"
+import { mapArray } from "solid-js";
function mapArray(
list: () => readonly T[],
mapFn: (v: T, i: () => number) => U
-): () => U[]
-
+): () => U[];
```
-Reactive map helper that caches each item by reference to reduce unnecessary mapping on updates.
-It only runs the mapping function once per value and then moves or removes it as needed.
+Reactive map helper that caches each item by reference to reduce unnecessary mapping on updates.
+It only runs the mapping function once per value and then moves or removes it as needed.
The index argument is a signal. The map function itself is not tracking.
Underlying helper for the `` control flow.
```ts
const mapped = mapArray(source, (model) => {
- const [name, setName] = createSignal(model.name)
- const [description, setDescription] = createSignal(model.description)
+ const [name, setName] = createSignal(model.name);
+ const [description, setDescription] = createSignal(model.description);
return {
id: model.id,
get name() {
- return name()
+ return name();
},
get description() {
- return description()
+ return description();
},
setName,
setDescription,
- }
-})
+ };
+});
```
## Arguments
diff --git a/src/routes/reference/reactive-utilities/merge-props.mdx b/src/routes/reference/reactive-utilities/merge-props.mdx
index 5027201f13..f7e43fda18 100644
--- a/src/routes/reference/reactive-utilities/merge-props.mdx
+++ b/src/routes/reference/reactive-utilities/merge-props.mdx
@@ -3,26 +3,25 @@ title: mergeProps
---
```ts
-import { mergeProps } from "solid-js"
-
-function mergeProps(...sources: any): any
+import { mergeProps } from "solid-js";
+function mergeProps(...sources: any): any;
```
-A reactive object **merge** method.
-Useful for setting default props for components in case caller doesn't provide them.
+A reactive object **merge** method.
+Useful for setting default props for components in case caller doesn't provide them.
Or cloning the props object including reactive properties.
-This method works by using a proxy and resolving properties in reverse order.
+This method works by using a proxy and resolving properties in reverse order.
This allows for dynamic tracking of properties that aren't present when the prop object is first merged.
```ts
// default props
-props = mergeProps({ name: "Smith" }, props)
+props = mergeProps({ name: "Smith" }, props);
// clone props
-newProps = mergeProps(props)
+newProps = mergeProps(props);
// merge props
-props = mergeProps(props, otherProps)
+props = mergeProps(props, otherProps);
```
diff --git a/src/routes/reference/reactive-utilities/observable.mdx b/src/routes/reference/reactive-utilities/observable.mdx
index 4e1bf23dfa..f6dab31c72 100644
--- a/src/routes/reference/reactive-utilities/observable.mdx
+++ b/src/routes/reference/reactive-utilities/observable.mdx
@@ -3,25 +3,24 @@ title: observable
---
```ts
-import { observable } from "solid-js"
-
-function observable(input: () => T): Observable
+import { observable } from "solid-js";
+function observable(input: () => T): Observable;
```
-This method takes a signal and produces an Observable.
+This method takes a signal and produces an Observable.
You can consume it from another Observable library of your choice, typically with the `from` operator.
```ts
// How to integrate rxjs with a Solid signal
-import { observable } from "solid-js"
-import { from } from "rxjs"
+import { observable } from "solid-js";
+import { from } from "rxjs";
-const [s, set] = createSignal(0)
+const [s, set] = createSignal(0);
-const obsv$ = from(observable(s))
+const obsv$ = from(observable(s));
-obsv$.subscribe((v) => console.log(v))
+obsv$.subscribe((v) => console.log(v));
```
You can also use `from` without rxjs; check out this [page](/reference/reactive-utilities/from).
diff --git a/src/routes/reference/reactive-utilities/on-util.mdx b/src/routes/reference/reactive-utilities/on-util.mdx
index 69af339ed6..1dcf7e44de 100644
--- a/src/routes/reference/reactive-utilities/on-util.mdx
+++ b/src/routes/reference/reactive-utilities/on-util.mdx
@@ -3,13 +3,13 @@ title: on
---
```ts
-import { on } from "solid-js"
+import { on } from "solid-js";
function on any> | (() => any), U>(
deps: T,
fn: (input: T, prevInput: T, prevValue?: U) => U,
options: { defer?: boolean } = {}
-): (prevValue?: U) => U | undefined
+): (prevValue?: U) => U | undefined;
```
`on` is designed to be passed into a computation to make its dependencies explicit.
@@ -37,8 +37,8 @@ setA("new"); // now it runs
## Using `on` with stores
:::info
- Please note that on stores and mutable, adding or removing a property from the
- parent object will trigger an effect. See [`createMutable`](/reference/store-utilities/create-mutable)
+Please note that on stores and mutable, adding or removing a property from the
+parent object will trigger an effect. See [`createMutable`](/reference/store-utilities/create-mutable)
:::
diff --git a/src/routes/reference/reactive-utilities/run-with-owner.mdx b/src/routes/reference/reactive-utilities/run-with-owner.mdx
index 10638849f6..45f9831004 100644
--- a/src/routes/reference/reactive-utilities/run-with-owner.mdx
+++ b/src/routes/reference/reactive-utilities/run-with-owner.mdx
@@ -10,34 +10,34 @@ import type { Owner } from "solid-js"
function runWithOwner(owner: Owner, fn: (() => void) => T): T
```
-Executes the given function under the provided owner, instead of (and without affecting) the owner of the outer scope.
-By default, computations created by `createEffect`, `createMemo`, etc. are owned by the owner of the currently executing code (the return value of `getOwner`), so in particular these will get disposed when their owner does.
+Executes the given function under the provided owner, instead of (and without affecting) the owner of the outer scope.
+By default, computations created by `createEffect`, `createMemo`, etc. are owned by the owner of the currently executing code (the return value of `getOwner`), so in particular these will get disposed when their owner does.
Calling `runWithOwner` provides a way to override this default to a manually specified owner (typically, the return value from a previous call to `getOwner`), enabling more precise control of when computations get disposed.
Having a (correct) owner is important for two reasons:
-- Computations without an owner cannot be cleaned up.
-For example, if you call `createEffect` without an owner (e.g., in the global scope), the effect will continue running forever, instead of being disposed when its owner gets disposed.
+- Computations without an owner cannot be cleaned up.
+ For example, if you call `createEffect` without an owner (e.g., in the global scope), the effect will continue running forever, instead of being disposed when its owner gets disposed.
-- `useContext` obtains context by walking up the owner tree to find the nearest ancestor providing the desired context.
-So without an owner you cannot look up any provided context (and with the wrong owner, you might obtain the wrong context).
+- `useContext` obtains context by walking up the owner tree to find the nearest ancestor providing the desired context.
+ So without an owner you cannot look up any provided context (and with the wrong owner, you might obtain the wrong context).
-Manually setting the owner is especially helpful when doing reactivity outside of any owner scope.
-In particular, asynchronous computation (via either `async` functions or callbacks like `setTimeout`) lose their automatically set owner, so remembering the original owner via `getOwner` and restoring it via `runWithOwner` is necessary in these cases.
+Manually setting the owner is especially helpful when doing reactivity outside of any owner scope.
+In particular, asynchronous computation (via either `async` functions or callbacks like `setTimeout`) lose their automatically set owner, so remembering the original owner via `getOwner` and restoring it via `runWithOwner` is necessary in these cases.
For example:
```ts
-const owner = getOwner()
+const owner = getOwner();
setTimeout(() => {
// This callback gets run without owner.
// Restore owner via runWithOwner:
runWithOwner(owner, () => {
- const foo = useContext(FooContext)
+ const foo = useContext(FooContext);
createEffect(() => {
- console.log(foo)
- })
- })
-}, 1000)
+ console.log(foo);
+ });
+ });
+}, 1000);
```
**Note:** that owners are not what determines dependency tracking, so `runWithOwner` does not help with tracking in asynchronous functions; use of reactive state in the asynchronous part (e.g. after the first `await`) will not be tracked as a dependency.
diff --git a/src/routes/reference/reactive-utilities/split-props.mdx b/src/routes/reference/reactive-utilities/split-props.mdx
index 3841792ce2..b366d64379 100644
--- a/src/routes/reference/reactive-utilities/split-props.mdx
+++ b/src/routes/reference/reactive-utilities/split-props.mdx
@@ -3,32 +3,31 @@ title: splitProps
---
```ts
-import { splitProps } from "solid-js"
+import { splitProps } from "solid-js";
function splitProps(
props: T,
...keys: Array<(keyof T)[]>
-): [...parts: Partial]
-
+): [...parts: Partial];
```
Splits a reactive object by keys.
-It takes a reactive object and any number of arrays of keys; for each array of keys, it will return a reactive object with just those properties of the original object.
+It takes a reactive object and any number of arrays of keys; for each array of keys, it will return a reactive object with just those properties of the original object.
The last reactive object in the returned array will have any leftover properties of the original object.
This can be useful if you want to consume a subset of props and pass the rest to a child.
```tsx
function MyComponent(props) {
- const [local, others] = splitProps(props, ["children"])
+ const [local, others] = splitProps(props, ["children"]);
return (
<>
{local.children}
>
- )
+ );
}
```
@@ -37,18 +36,18 @@ Because `splitProps` takes any number of arrays, we can split a props object as
Let's say a component was passed six props:
```tsx
-;
+;
// ...
function MyComponent(props) {
- console.log(props) // {a: 1, b: 2, c: 3, d: 4, e: 5, foo: "bar"}
+ console.log(props); // {a: 1, b: 2, c: 3, d: 4, e: 5, foo: "bar"}
const [vowels, consonants, leftovers] = splitProps(
props,
["a", "e"],
["b", "c", "d"]
- )
- console.log(vowels) // {a: 1, e: 5}
- console.log(consonants) // {b: 2, c: 3, d: 4}
- console.log(leftovers.foo) // bar
+ );
+ console.log(vowels); // {a: 1, e: 5}
+ console.log(consonants); // {b: 2, c: 3, d: 4}
+ console.log(leftovers.foo); // bar
}
```
diff --git a/src/routes/reference/reactive-utilities/start-transition.mdx b/src/routes/reference/reactive-utilities/start-transition.mdx
index 2abdf9dadd..530e9546c0 100644
--- a/src/routes/reference/reactive-utilities/start-transition.mdx
+++ b/src/routes/reference/reactive-utilities/start-transition.mdx
@@ -9,5 +9,5 @@ function startTransition: (fn: () => void) => Promise
```
-Similar to `useTransition` except there is no associated pending state.
+Similar to `useTransition` except there is no associated pending state.
This one can just be used directly to start the Transition.
diff --git a/src/routes/reference/reactive-utilities/untrack.mdx b/src/routes/reference/reactive-utilities/untrack.mdx
index b73d87b8d8..72c7f0f0bb 100644
--- a/src/routes/reference/reactive-utilities/untrack.mdx
+++ b/src/routes/reference/reactive-utilities/untrack.mdx
@@ -32,6 +32,7 @@ export function Component(props) {
}
}
```
+
-
\ No newline at end of file
+
diff --git a/src/routes/reference/reactive-utilities/use-transition.mdx b/src/routes/reference/reactive-utilities/use-transition.mdx
index 97b085731f..8977209d96 100644
--- a/src/routes/reference/reactive-utilities/use-transition.mdx
+++ b/src/routes/reference/reactive-utilities/use-transition.mdx
@@ -3,16 +3,15 @@ title: useTransition
---
```ts
-import { useTransition } from "solid-js"
+import { useTransition } from "solid-js";
function useTransition(): [
pending: () => boolean,
- startTransition: (fn: () => void) => Promise
-]
-
+ startTransition: (fn: () => void) => Promise,
+];
```
-Used to batch async updates in a transaction deferring commit until all async processes are complete.
+Used to batch async updates in a transaction deferring commit until all async processes are complete.
This is tied into Suspense and only tracks resources read under Suspense boundaries.
```ts
diff --git a/src/routes/reference/rendering/dev.mdx b/src/routes/reference/rendering/dev.mdx
index 39cf81e4fa..8229871687 100644
--- a/src/routes/reference/rendering/dev.mdx
+++ b/src/routes/reference/rendering/dev.mdx
@@ -3,15 +3,15 @@ title: DEV
---
```ts
-import { DEV } from "solid-js"
+import { DEV } from "solid-js";
-const DEV: object | undefined
+const DEV: object | undefined;
```
-On the client, Solid provides (via [conditional exports](https://nodejs.org/api/packages.html#conditional-exports)) different builds depending on whether the **development** condition is set.
+On the client, Solid provides (via [conditional exports](https://nodejs.org/api/packages.html#conditional-exports)) different builds depending on whether the **development** condition is set.
Development mode provides some additional checking β e.g. detecting accidental use of multiple instances of Solid β which are removed in production builds.
-If you want code to run only in development mode (most useful in libraries), you can check whether the **DEV** export is defined.
+If you want code to run only in development mode (most useful in libraries), you can check whether the **DEV** export is defined.
Note that it is always defined on the server, so you may want to combine with [isServer](/reference/rendering/is-server):
```ts
diff --git a/src/routes/reference/rendering/hydrate.mdx b/src/routes/reference/rendering/hydrate.mdx
index 31ce37db1f..a532014197 100644
--- a/src/routes/reference/rendering/hydrate.mdx
+++ b/src/routes/reference/rendering/hydrate.mdx
@@ -3,30 +3,29 @@ title: hydrate
---
```ts
-import { hydrate } from "solid-js/web"
-import type { JSX } from "solid-js"
-import type { MountableElement } from "solid-js/web"
+import { hydrate } from "solid-js/web";
+import type { JSX } from "solid-js";
+import type { MountableElement } from "solid-js/web";
function hydrate(
- fn: () => JSX.Element,
- node: MountableElement,
- options?: { renderId?: string; owner?: unknown }
-): () => void
-
+ fn: () => JSX.Element,
+ node: MountableElement,
+ options?: { renderId?: string; owner?: unknown }
+): () => void;
```
-This method is similar to `render` except that it attempts to rehydrate what is already rendered to the DOM.
+This method is similar to `render` except that it attempts to rehydrate what is already rendered to the DOM.
When initializing in the browser a page has already been server rendered.
```ts
-const dispose = hydrate(App, document.getElementById("app"))
+const dispose = hydrate(App, document.getElementById("app"));
```
## Parameters
-| Prop | type | description |
-| -------------------- | ------------------ | ----------------------------------------------- |
-| fn | `() => JSX.Element`| Function that returns the application code. |
-| node | MountableElement | DOM Element to mount the application to |
-| options.renderId | string | |
-| options.owner | unknown | |
\ No newline at end of file
+| Prop | type | description |
+| ---------------- | ------------------- | ------------------------------------------- |
+| fn | `() => JSX.Element` | Function that returns the application code. |
+| node | MountableElement | DOM Element to mount the application to |
+| options.renderId | string | |
+| options.owner | unknown | |
diff --git a/src/routes/reference/rendering/hydration-script.mdx b/src/routes/reference/rendering/hydration-script.mdx
index 3448d9041c..71db5c0d3d 100644
--- a/src/routes/reference/rendering/hydration-script.mdx
+++ b/src/routes/reference/rendering/hydration-script.mdx
@@ -3,24 +3,23 @@ title: hydrationScript
---
```ts
-import { generateHydrationScript, HydrationScript } from "solid-js/web"
-import type { JSX } from "solid-js"
+import { generateHydrationScript, HydrationScript } from "solid-js/web";
+import type { JSX } from "solid-js";
function generateHydrationScript(options: {
- nonce?: string
- eventNames?: string[]
-}): string
+ nonce?: string;
+ eventNames?: string[];
+}): string;
function HydrationScript(props: {
- nonce?: string
- eventNames?: string[]
-}): JSX.Element
-
+ nonce?: string;
+ eventNames?: string[];
+}): JSX.Element;
```
-Hydration Script is a special script that should be placed once on the page to bootstrap hydration before Solid's runtime has loaded.
+Hydration Script is a special script that should be placed once on the page to bootstrap hydration before Solid's runtime has loaded.
It comes both as a function that can be called and inserted in an HTML string, or as a Component if you are rendering JSX from the `` tag.
-The options are for the **nonce** to be put on the script tag and any event names for that Solid should capture before scripts have loaded and replay during hydration.
-These events are limited to those that Solid delegates which include most UI Events that are composed and bubble.
+The options are for the **nonce** to be put on the script tag and any event names for that Solid should capture before scripts have loaded and replay during hydration.
+These events are limited to those that Solid delegates which include most UI Events that are composed and bubble.
By default it is only click and input events.
diff --git a/src/routes/reference/rendering/is-server.mdx b/src/routes/reference/rendering/is-server.mdx
index 4a8539ab26..35fee9275b 100644
--- a/src/routes/reference/rendering/is-server.mdx
+++ b/src/routes/reference/rendering/is-server.mdx
@@ -3,13 +3,12 @@ title: isServer
---
```ts
-import { isServer } from "solid-js/web"
-
-const isServer: boolean
+import { isServer } from "solid-js/web";
+const isServer: boolean;
```
-This indicates that the code is being run as the server or browser bundle.
+This indicates that the code is being run as the server or browser bundle.
As the underlying runtimes export this as a constant boolean it allows bundlers to eliminate the code and their used imports from the respective bundles.
```ts
diff --git a/src/routes/reference/rendering/render-to-stream.mdx b/src/routes/reference/rendering/render-to-stream.mdx
index 8a92e23f8c..5da7da3b44 100644
--- a/src/routes/reference/rendering/render-to-stream.mdx
+++ b/src/routes/reference/rendering/render-to-stream.mdx
@@ -3,21 +3,20 @@ title: renderToStream
---
```ts
-import { renderToStream } from "solid-js/web"
+import { renderToStream } from "solid-js/web";
function renderToStream(
fn: () => T,
options?: {
- nonce?: string
- renderId?: string
- onCompleteShell?: () => void
- onCompleteAll?: () => void
+ nonce?: string;
+ renderId?: string;
+ onCompleteShell?: () => void;
+ onCompleteAll?: () => void;
}
): {
- pipe: (writable: { write: (v: string) => void }) => void
- pipeTo: (writable: WritableStream) => void
-}
-
+ pipe: (writable: { write: (v: string) => void }) => void;
+ pipeTo: (writable: WritableStream) => void;
+};
```
This method renders to a stream.
@@ -25,11 +24,11 @@ It renders the content synchronously including any Suspense fallback placeholder
```ts
// node
-renderToStream(App).pipe(res)
+renderToStream(App).pipe(res);
// web stream
-const { readable, writable } = new TransformStream()
-renderToStream(App).pipeTo(writable)
+const { readable, writable } = new TransformStream();
+renderToStream(App).pipeTo(writable);
```
`onCompleteShell` fires when synchronous rendering is complete before writing the first flush to the stream out to the browser.
@@ -37,8 +36,8 @@ renderToStream(App).pipeTo(writable)
`renderId` is used to namespace renders when having multiple top level roots.
:::info
- This API replaces the previous pipeToWritable and pipeToNodeWritable
- APIs.
+This API replaces the previous pipeToWritable and pipeToNodeWritable
+APIs.
:::
## Options
diff --git a/src/routes/reference/rendering/render-to-string-async.mdx b/src/routes/reference/rendering/render-to-string-async.mdx
index 16c2509eb2..dd7129143d 100644
--- a/src/routes/reference/rendering/render-to-string-async.mdx
+++ b/src/routes/reference/rendering/render-to-string-async.mdx
@@ -3,26 +3,25 @@ title: renderToStringAsync
---
```ts
-import { renderToStringAsync } from "solid-js/web"
+import { renderToStringAsync } from "solid-js/web";
function renderToStringAsync(
fn: () => T,
options?: {
- timeoutMs?: number
- renderId?: string
- nonce?: string
+ timeoutMs?: number;
+ renderId?: string;
+ nonce?: string;
}
-): Promise
-
+): Promise;
```
-Same as `renderToString` except that it will wait for all `` boundaries to resolve before returning the results.
+Same as `renderToString` except that it will wait for all `` boundaries to resolve before returning the results.
Resource data is automatically serialized into the script tag and will be hydrated on client load.
`renderId` is used to namespace renders when having multiple top level roots.
```ts
-const html = await renderToStringAsync(App)
+const html = await renderToStringAsync(App);
```
## Options
diff --git a/src/routes/reference/rendering/render-to-string.mdx b/src/routes/reference/rendering/render-to-string.mdx
index 454b0c9718..3b669ecaf3 100644
--- a/src/routes/reference/rendering/render-to-string.mdx
+++ b/src/routes/reference/rendering/render-to-string.mdx
@@ -3,26 +3,25 @@ title: renderToString
---
```ts
-import { renderToString } from "solid-js/web"
+import { renderToString } from "solid-js/web";
function renderToString(
fn: () => T,
options?: {
- nonce?: string
- renderId?: string
+ nonce?: string;
+ renderId?: string;
}
-): string
-
+): string;
```
-Renders to a string synchronously.
-The function also generates a script tag for progressive hydration.
+Renders to a string synchronously.
+The function also generates a script tag for progressive hydration.
Options include eventNames to listen to before the page loads and play back on hydration, and nonce to put on the script tag.
`renderId` is used to namespace renders when having multiple top level roots.
```ts
-const html = renderToString(App)
+const html = renderToString(App);
```
## Options
diff --git a/src/routes/reference/rendering/render.mdx b/src/routes/reference/rendering/render.mdx
index f30f5b2976..fde3c78d14 100644
--- a/src/routes/reference/rendering/render.mdx
+++ b/src/routes/reference/rendering/render.mdx
@@ -3,19 +3,15 @@ title: render
---
```ts
-import { render } from "solid-js/web"
-import type { JSX } from "solid-js"
-import type { MountableElement } from "solid-js/web"
-
-function render(
- code: () => JSX.Element,
- element: MountableElement
-): () => void
+import { render } from "solid-js/web";
+import type { JSX } from "solid-js";
+import type { MountableElement } from "solid-js/web";
+function render(code: () => JSX.Element, element: MountableElement): () => void;
```
-This is the browser app entry point.
-Provide a top-level component function and an element to mount to.
+This is the browser app entry point.
+Provide a top-level component function and an element to mount to.
It is recommended this element be empty: while `render` will just append children, the returned dispose function will remove all children.
```ts
@@ -28,7 +24,7 @@ It's important that the first argument is a function: do not pass JSX directly (
## Parameters
-| Argument | Type | Description |
-| -------------------- | ------------------- | ----------------------------------------------- |
-| code | `() => JSX.Element` | Function that returns the application code. |
-| element | MountableElement | DOM Element to mount the application to |
\ No newline at end of file
+| Argument | Type | Description |
+| -------- | ------------------- | ------------------------------------------- |
+| code | `() => JSX.Element` | Function that returns the application code. |
+| element | MountableElement | DOM Element to mount the application to |
diff --git a/src/routes/reference/secondary-primitives/create-computed.mdx b/src/routes/reference/secondary-primitives/create-computed.mdx
index bd565ff381..cbe7ebc4ad 100644
--- a/src/routes/reference/secondary-primitives/create-computed.mdx
+++ b/src/routes/reference/secondary-primitives/create-computed.mdx
@@ -3,24 +3,23 @@ title: createComputed
---
```ts
-import { createComputed } from "solid-js"
-
-function createComputed(fn: (v: T) => T, value?: T): void
+import { createComputed } from "solid-js";
+function createComputed(fn: (v: T) => T, value?: T): void;
```
-`createComputed` creates a new computation that immediately runs the given function in a tracking scope, thus automatically tracking its dependencies, and automatically reruns the function whenever the dependencies changes.
-The function gets called with an argument equal to the value returned from the function's last execution, or on the first call, equal to the optional second argument to `createComputed`.
+`createComputed` creates a new computation that immediately runs the given function in a tracking scope, thus automatically tracking its dependencies, and automatically reruns the function whenever the dependencies changes.
+The function gets called with an argument equal to the value returned from the function's last execution, or on the first call, equal to the optional second argument to `createComputed`.
Note that the return value of the function is not otherwise exposed; in particular, createComputed has no return value.
-`createComputed` is the most immediate form of reactivity in Solid, and is most useful for building other reactive primitives.
-For example, some other Solid primitives are built from `createComputed`.
-However, it should be used with care, as `createComputed` can easily cause more unnecessary updates than other reactive primitives.
+`createComputed` is the most immediate form of reactivity in Solid, and is most useful for building other reactive primitives.
+For example, some other Solid primitives are built from `createComputed`.
+However, it should be used with care, as `createComputed` can easily cause more unnecessary updates than other reactive primitives.
Before using it, consider the closely related primitives [`createMemo`](/reference/basic-reactivity/create-memo) and [`createRenderEffect`](/reference/secondary-primitives/create-render-effect).
-Like `createMemo`, `createComputed` calls its function immediately on updates (unless you're in a [batch](/reference/reactive-utilities/batch), [effect](/reference/basic-reactivity/create-effect), or [transition](/reference/reactive-utilities/use-transition)).
-However, while `createMemo` functions should be pure (not set any signals), `createComputed` functions can set signals.
-Related, `createMemo` offers a readonly signal for the return value of the function, whereas to do the same with `createComputed` you would need to set a signal within the function.
+Like `createMemo`, `createComputed` calls its function immediately on updates (unless you're in a [batch](/reference/reactive-utilities/batch), [effect](/reference/basic-reactivity/create-effect), or [transition](/reference/reactive-utilities/use-transition)).
+However, while `createMemo` functions should be pure (not set any signals), `createComputed` functions can set signals.
+Related, `createMemo` offers a readonly signal for the return value of the function, whereas to do the same with `createComputed` you would need to set a signal within the function.
If it is possible to use pure functions and `createMemo`, this is likely more efficient, as Solid optimizes the execution order of memo updates, whereas updating a signal within `createComputed` will immediately trigger reactive updates some of which may turn out to be unnecessary.
## Arguments
diff --git a/src/routes/reference/secondary-primitives/create-deferred.mdx b/src/routes/reference/secondary-primitives/create-deferred.mdx
index d62f43b088..e3e279ec99 100644
--- a/src/routes/reference/secondary-primitives/create-deferred.mdx
+++ b/src/routes/reference/secondary-primitives/create-deferred.mdx
@@ -3,20 +3,19 @@ title: createDeferred
---
```ts
-import { createDeferred } from "solid-js"
+import { createDeferred } from "solid-js";
function createDeferred(
source: () => T,
options?: {
- timeoutMs?: number
- equals?: false | ((prev: T, next: T) => boolean)
- name?: string
+ timeoutMs?: number;
+ equals?: false | ((prev: T, next: T) => boolean);
+ name?: string;
}
-): () => T
-
+): () => T;
```
-Creates a readonly that only notifies downstream changes when the browser is idle.
+Creates a readonly that only notifies downstream changes when the browser is idle.
`timeoutMs` is the maximum time to wait before forcing the update.
## Options
@@ -26,4 +25,3 @@ Creates a readonly that only notifies downstream changes when the browser is idl
| timeoutMs | `number` | The maximum time to wait before forcing the update. |
| equals | `false or ((prev: T, next: T) => boolean)` | A function that returns true if the value has changed. |
| name | `string` | The name of the readonly. |
-
diff --git a/src/routes/reference/secondary-primitives/create-reaction.mdx b/src/routes/reference/secondary-primitives/create-reaction.mdx
index 9a49a35c1f..376def1d5d 100644
--- a/src/routes/reference/secondary-primitives/create-reaction.mdx
+++ b/src/routes/reference/secondary-primitives/create-reaction.mdx
@@ -3,24 +3,23 @@ title: createReaction
---
```ts
-import { createReaction } from "solid-js"
-
-function createReaction(onInvalidate: () => void): (fn: () => void) => void
+import { createReaction } from "solid-js";
+function createReaction(onInvalidate: () => void): (fn: () => void) => void;
```
-Sometimes it is useful to separate tracking from re-execution.
+Sometimes it is useful to separate tracking from re-execution.
This primitive registers a side effect that is run the first time the expression wrapped by the returned tracking function is notified of a change.
```ts
-const [s, set] = createSignal("start")
+const [s, set] = createSignal("start");
-const track = createReaction(() => console.log("something"))
+const track = createReaction(() => console.log("something"));
// run the reaction next time `s` changes.
-track(() => s())
+track(() => s());
-set("end") // "something"
+set("end"); // "something"
-set("final") // no-op since the reaction only runs on the first update, need to call `track` again.
+set("final"); // no-op since the reaction only runs on the first update, need to call `track` again.
```
diff --git a/src/routes/reference/secondary-primitives/create-render-effect.mdx b/src/routes/reference/secondary-primitives/create-render-effect.mdx
index bf8a77852f..5b4fbc5c18 100644
--- a/src/routes/reference/secondary-primitives/create-render-effect.mdx
+++ b/src/routes/reference/secondary-primitives/create-render-effect.mdx
@@ -3,40 +3,39 @@ title: createRenderEffect
---
```ts
-import { createRenderEffect } from "solid-js"
-
-function createRenderEffect(fn: (v: T) => T, value?: T): void
+import { createRenderEffect } from "solid-js";
+function createRenderEffect(fn: (v: T) => T, value?: T): void;
```
-A render effect is a computation similar to a regular effect (as created by [`createEffect`](/reference/basic-reactivity/create-effect)), but differs in when Solid schedules the first execution of the effect function.
-While `createEffect` waits for the current rendering phase to be complete, `createRenderEffect` immediately calls the function.
-Thus the effect runs as DOM elements are being created and updated, but possibly before specific elements of interest have been created, and probably before those elements have been connected to the document.
-In particular, **refs** will not be set before the initial effect call.
+A render effect is a computation similar to a regular effect (as created by [`createEffect`](/reference/basic-reactivity/create-effect)), but differs in when Solid schedules the first execution of the effect function.
+While `createEffect` waits for the current rendering phase to be complete, `createRenderEffect` immediately calls the function.
+Thus the effect runs as DOM elements are being created and updated, but possibly before specific elements of interest have been created, and probably before those elements have been connected to the document.
+In particular, **refs** will not be set before the initial effect call.
Indeed, Solid uses `createRenderEffect` to implement the rendering phase itself, including setting of **refs**.
-Reactive updates to render effects are identical to effects: they queue up in response to a reactive change (e.g., a single signal update, or a batch of changes, or collective changes during an entire render phase) and run in a single [`batch`](/reference/reactive-utilities/batch) afterward (together with effects).
+Reactive updates to render effects are identical to effects: they queue up in response to a reactive change (e.g., a single signal update, or a batch of changes, or collective changes during an entire render phase) and run in a single [`batch`](/reference/reactive-utilities/batch) afterward (together with effects).
In particular, all signal updates within a render effect are batched.
Here is an example of the behavior. (Compare with the example in [`createEffect`](/reference/basic-reactivity/create-effect).)
```ts
// assume this code is in a component function, so is part of a rendering phase
-const [count, setCount] = createSignal(0)
+const [count, setCount] = createSignal(0);
// this effect prints count at the beginning and when it changes
-createRenderEffect(() => console.log("count =", count()))
+createRenderEffect(() => console.log("count =", count()));
// render effect runs immediately, printing `count = 0`
-console.log("hello")
-setCount(1) // effect won't run yet
-setCount(2) // effect won't run yet
+console.log("hello");
+setCount(1); // effect won't run yet
+setCount(2); // effect won't run yet
queueMicrotask(() => {
// now `count = 2` will print
- console.log("microtask")
- setCount(3) // immediately prints `count = 3`
- console.log("goodbye")
-})
+ console.log("microtask");
+ setCount(3); // immediately prints `count = 3`
+ console.log("goodbye");
+});
// --- overall output: ---
// count = 0 [this is the only added line compared to createEffect]
diff --git a/src/routes/reference/secondary-primitives/create-selector.mdx b/src/routes/reference/secondary-primitives/create-selector.mdx
index 8b5c0ade0b..e1baf46711 100644
--- a/src/routes/reference/secondary-primitives/create-selector.mdx
+++ b/src/routes/reference/secondary-primitives/create-selector.mdx
@@ -3,12 +3,12 @@ title: createSelector
---
```ts
-import { createSelector } from "solid-js"
+import { createSelector } from "solid-js";
function createSelector(
source: () => T,
fn?: (a: U, b: T) => boolean
-): (key: U) => boolean
+): (key: U) => boolean;
```
Creates a parameterized derived boolean signal `selector(key)` that indicates
@@ -16,13 +16,13 @@ whether `key` is equal to the current value of the `source` signal.
These signals are optimized to notify each subscriber only when their `key`
starts or stops matching the reactive `source` value
(instead of every time `key` changes).
-If you have *n* different subscribers with different keys,
+If you have _n_ different subscribers with different keys,
and the `source` value changes from `a` to `b`, then
-instead of all *n* subscribers updating,
+instead of all _n_ subscribers updating,
at most two subscribers will update:
the signal with key `a` will change to `false`,
and the signal with key `b` will change to `true`.
-Thus it reduces from *n* updates to 2 updates.
+Thus it reduces from _n_ updates to 2 updates.
Useful for defining the selection state of several selectable elements.
For example:
@@ -39,7 +39,7 @@ const isSelected = createSelector(selectedId)
In the code above, each `li` element receives an `active` class
exactly when the corresponding `item.id` is equal to `selectedId()`.
When the `selectedId` signal changes, the `li` element(s) that previously
-had previously matching `id` get the `active` class removed, and the
+had previously matching `id` get the `active` class removed, and the
`li` element(s) that now have a matching `id` get the `active` class added.
All other `li` elements get skipped, so if `id`s are distinct,
only 2 DOM operations get performed.
@@ -57,7 +57,7 @@ const [selectedId, setSelectedId] = createSignal()
## Arguments
-| Name | Type | Description |
-| :------- | :------------------------ | :------------------------------------------- |
-| `source` | `() => T` | The source signal to get the value from and compare with keys. |
+| Name | Type | Description |
+| :------- | :------------------------ | :------------------------------------------------------------------------------------------------------------- |
+| `source` | `() => T` | The source signal to get the value from and compare with keys. |
| `fn` | `(a: U, b: T) => boolean` | A function to compare the key and the value, returning whether they should be treated as equal. Default: `===` |
diff --git a/src/routes/reference/server-utilities/data.json b/src/routes/reference/server-utilities/data.json
index 5f09a10a82..3d47aead9f 100644
--- a/src/routes/reference/server-utilities/data.json
+++ b/src/routes/reference/server-utilities/data.json
@@ -1,6 +1,4 @@
{
"title": "Server utilities",
- "pages": [
- "get-request-event.mdx"
- ]
+ "pages": ["get-request-event.mdx"]
}
diff --git a/src/routes/reference/server-utilities/get-request-event.mdx b/src/routes/reference/server-utilities/get-request-event.mdx
index 44954ecdc3..82ab6fc1af 100644
--- a/src/routes/reference/server-utilities/get-request-event.mdx
+++ b/src/routes/reference/server-utilities/get-request-event.mdx
@@ -16,9 +16,9 @@ function getRequestEvent(): RequestEvent | undefined
You can retrieve the request event by calling `getRequestEvent`:
```js
-import { getRequestEvent } from "solid-js/web"
+import { getRequestEvent } from "solid-js/web";
-const event = getRequestEvent()
+const event = getRequestEvent();
```
## Request
@@ -26,10 +26,10 @@ const event = getRequestEvent()
`.request` is the most important property of the `RequestEvent`.
This is a Web [Request object](https://developer.mozilla.org/en-US/docs/Web/API/Request) that represents the current request to the server.
You can access properties off of it such as `url` and `headers`.
- `body`, however, does not typically need to be handled directly for things such as server functions or rendering, which already handle mapping.
+`body`, however, does not typically need to be handled directly for things such as server functions or rendering, which already handle mapping.
```js
-import { getRequestEvent } from "solid-js/web"
+import { getRequestEvent } from "solid-js/web";
const event = getRequestEvent();
if (event) {
@@ -43,7 +43,7 @@ The `getRequestEvent` can also be used to stub out the Response - this extends t
This is kept up to date so it can be used to read and write headers and status for the current response.
```js
-import { getRequestEvent } from "solid-js/web"
+import { getRequestEvent } from "solid-js/web";
const event = getRequestEvent();
if (event) {
@@ -63,6 +63,6 @@ This is important because some headers previously set may not be needed to be se
**Note:** This is important to keep in mind when choosing where to set headers and responses.
:::info[Usage with SolidStart]
- See this guide on [Request
- Events](/solid-start/advanced/request-events).
+See this guide on [Request
+Events](/solid-start/advanced/request-events).
:::
diff --git a/src/routes/reference/store-utilities/create-mutable.mdx b/src/routes/reference/store-utilities/create-mutable.mdx
index 5c53aac82f..c6b27c4ca0 100644
--- a/src/routes/reference/store-utilities/create-mutable.mdx
+++ b/src/routes/reference/store-utilities/create-mutable.mdx
@@ -7,21 +7,22 @@ title: createMutable
By intercepting property access, it allows automatic tracking of deep nesting via proxy making it useful for integrating external systems or serving as a compatibility layer with frameworks like MobX or Vue.
```tsx
-import { createMutable } from "solid-js/store"
-import type { Store, StoreNode } from "solid-js/store"
+import { createMutable } from "solid-js/store";
+import type { Store, StoreNode } from "solid-js/store";
function createMutable(state: T | Store): Store;
```
:::info
- It's important to recognize that a mutable state, which can be passed around and modified anywhere, may complicate the code structure and increase the risk of breaking unidirectional flow.
+It's important to recognize that a mutable state, which can be passed around and modified anywhere, may complicate the code structure and increase the risk of breaking unidirectional flow.
+
+ For a more robust alternative, it is generally recommended to use `createStore` instead.
+ Additionally, the [`produce`](/reference/store-utilities/produce) utility can provide many of these same benefits without the associated downsides.
- For a more robust alternative, it is generally recommended to use `createStore` instead.
- Additionally, the [`produce`](/reference/store-utilities/produce) utility can provide many of these same benefits without the associated downsides.
:::
```tsx
-import { createMutable } from "solid-js/store"
+import { createMutable } from "solid-js/store";
const state = createMutable({
someValue: 0,
diff --git a/src/routes/reference/store-utilities/create-store.mdx b/src/routes/reference/store-utilities/create-store.mdx
index c084231aac..cdc53eab20 100644
--- a/src/routes/reference/store-utilities/create-store.mdx
+++ b/src/routes/reference/store-utilities/create-store.mdx
@@ -7,8 +7,8 @@ Stores were intentionally designed to manage data structures like objects and ar
## Types Signature
```tsx
-import { createStore } from "solid-js/store"
-import type { StoreNode, Store, SetStoreFunction } from "solid-js/store"
+import { createStore } from "solid-js/store";
+import type { StoreNode, Store, SetStoreFunction } from "solid-js/store";
function createStore(
state: T | Store
diff --git a/src/routes/reference/store-utilities/modify-mutable.mdx b/src/routes/reference/store-utilities/modify-mutable.mdx
index ac56213047..ab3945ae5e 100644
--- a/src/routes/reference/store-utilities/modify-mutable.mdx
+++ b/src/routes/reference/store-utilities/modify-mutable.mdx
@@ -7,9 +7,9 @@ title: modifyMutable
It operates within a single [`batch`](/reference/reactive-utilities/batch), ensuring that dependent computations are updated just once, rather than triggering updates for each individual change.
```tsx
-import { modifyMutable } from "solid-js/store"
+import { modifyMutable } from "solid-js/store";
-function modifyMutable(mutable: T, modifier: (state: T) => T): void
+function modifyMutable(mutable: T, modifier: (state: T) => T): void;
```
The function takes two arguments:
@@ -18,14 +18,14 @@ The function takes two arguments:
2. The second argument is a Store modifier, which could be one of those returned by [`reconcile`](/reference/store-utilities/reconcile).
:::caution
- When passing in your own modifier function, it's important to be aware that
- its argument is an unwrapped version of the store.
+When passing in your own modifier function, it's important to be aware that
+its argument is an unwrapped version of the store.
:::
For example, if the UI depends on multiple fields of a mutable:
```tsx
-import { createMutable } from "solid-js/store"
+import { createMutable } from "solid-js/store";
const state = createMutable({
user: {
@@ -47,7 +47,7 @@ state.user.lastName = "Doe";
To trigger just a single update, the fields can be modified using a `batch`:
```tsx
-import { batch } from "solid-js"
+import { batch } from "solid-js";
batch(() => {
state.user.firstName = "Jane";
@@ -58,7 +58,7 @@ batch(() => {
`modifyMutable` combined with [`reconcile`](/reference/store-utilities/reconcile) or [`produce`](/reference/store-utilities/produce) provides two alternate ways to do similar things:
```tsx
-import { modifyMutable, reconcile } from "solid-js/store"
+import { modifyMutable, reconcile } from "solid-js/store";
// Replace state.user with the specified object (deleting any other fields)
modifyMutable(
@@ -71,7 +71,7 @@ modifyMutable(
```
```tsx
-import { modifyMutable, produce } from "solid-js/store"
+import { modifyMutable, produce } from "solid-js/store";
// Modify two fields in a batch, triggering just one update
modifyMutable(
diff --git a/src/routes/reference/store-utilities/produce.mdx b/src/routes/reference/store-utilities/produce.mdx
index 1f0153fc5d..a7ef3b2ace 100644
--- a/src/routes/reference/store-utilities/produce.mdx
+++ b/src/routes/reference/store-utilities/produce.mdx
@@ -5,8 +5,8 @@ title: produce
`produce` is an [Immer](https://immerjs.github.io/immer/) inspired API for Solid's Store objects that allows for localized mutation.
```ts
-import { produce } from "solid-js/store"
-import type { NotWrappable, Store } from "solid-js/store"
+import { produce } from "solid-js/store";
+import type { NotWrappable, Store } from "solid-js/store";
function produce(
fn: (state: T) => void
diff --git a/src/routes/reference/store-utilities/reconcile.mdx b/src/routes/reference/store-utilities/reconcile.mdx
index cfd0e7d946..48ca59019f 100644
--- a/src/routes/reference/store-utilities/reconcile.mdx
+++ b/src/routes/reference/store-utilities/reconcile.mdx
@@ -2,12 +2,12 @@
title: reconcile
---
-`reconcile` is designed for diffing data changes in situations where granular updates cannot be applied.
+`reconcile` is designed for diffing data changes in situations where granular updates cannot be applied.
This is useful when dealing with immutable data from stores or handling large API responses.
```tsx
-import { reconcile } from "solid-js/store"
-import type { NotWrappable, Store } from "solid-js/store"
+import { reconcile } from "solid-js/store";
+import type { NotWrappable, Store } from "solid-js/store";
function reconcile(
value: T | Store,
@@ -17,14 +17,14 @@ function reconcile(
} = { key: "id" }
): (
state: T extends NotWrappable ? T : Store
-) => T extends NotWrappable ? T : Store
+) => T extends NotWrappable ? T : Store;
```
`reconcile` has a `key` option that can be used when available to match items.
-The `value` accepts either a value of type `T` or a Store containing values of type `T`.
+The `value` accepts either a value of type `T` or a Store containing values of type `T`.
This represents the data to be reconciled.
-The `reconcile` function helps manage data changes by performing a diffing process, making it particularly handy in scenarios where applying granular updates is challenging or inefficient.
+The `reconcile` function helps manage data changes by performing a diffing process, making it particularly handy in scenarios where applying granular updates is challenging or inefficient.
The `key` and `merge` options provide flexibility to customize the reconciliation process based on specific needs.
@@ -39,7 +39,7 @@ onCleanup(() => unsubscribe());
##### Options
-| Option | Type | Default | Description |
-| ------ | ------- | ------- | ---------------------------------- |
-| key | string | "id" | Specifies the key to be used for matching items during reconciliation |
+| Option | Type | Default | Description |
+| ------ | ------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| key | string | "id" | Specifies the key to be used for matching items during reconciliation |
| merge | boolean | false | When merge is false, referential checks are performed where possible to determine equality, and items that are not referentially equal are replaced. When merge is true, all diffing is pushed to the leaves, effectively morphing the previous data to the new value. |
diff --git a/src/routes/reference/store-utilities/unwrap.mdx b/src/routes/reference/store-utilities/unwrap.mdx
index 64742a17ef..cb4bbccbae 100644
--- a/src/routes/reference/store-utilities/unwrap.mdx
+++ b/src/routes/reference/store-utilities/unwrap.mdx
@@ -5,8 +5,8 @@ title: unwrap
`unwrap` returns the underlying data in the store without a proxy.
```tsx
-import { unwrap } from "solid-js/store"
-import type { Store } from "solid-js/store"
+import { unwrap } from "solid-js/store";
+import type { Store } from "solid-js/store";
-function unwrap(store: Store): T
+function unwrap(store: Store): T;
```
diff --git a/src/routes/solid-meta/getting-started/installation-and-setup.mdx b/src/routes/solid-meta/getting-started/installation-and-setup.mdx
index 1e09b57f87..3f4b6bae18 100644
--- a/src/routes/solid-meta/getting-started/installation-and-setup.mdx
+++ b/src/routes/solid-meta/getting-started/installation-and-setup.mdx
@@ -19,17 +19,9 @@ npm i @solidjs/meta
```
-
```bash frame="none"
@@ -42,15 +34,18 @@ deno add npm:@solidjs/meta
1. Wrap your application with [``](/solid-meta/reference/meta/metaprovider)
2. To include head tags within your application, render any of the following:
- 1. [``](/solid-meta/reference/meta/title): Adds the `title` of the page.
- 2. [``](/solid-meta/reference/meta/meta): Adds extra metadata to the page.
- 3. [``](/solid-meta/reference/meta/style): Adds a `style` element to the page.
- 4. [``](/solid-meta/reference/meta/link): Specifies a relationship between the page and an external resource.
- 5. [``](/solid-meta/reference/meta/base): Specifies the base URL for all relative URLs in the document.
+ 1. [``](/solid-meta/reference/meta/title): Adds the `title` of the page.
+ 2. [``](/solid-meta/reference/meta/meta): Adds extra metadata to the page.
+ 3. [``](/solid-meta/reference/meta/style): Adds a `style` element to the page.
+ 4. [``](/solid-meta/reference/meta/link): Specifies a relationship between the page and an external resource.
+ 5. [``](/solid-meta/reference/meta/base): Specifies the base URL for all relative URLs in the document.
+
- These components can be used multiple times within the application.
+
3. If using Solid on the server with JSX, no additional configuration is required.
Here is an example of how your code might look after this setup.
+
```js
import { MetaProvider, Title, Link, Meta } from "@solidjs/meta";
@@ -64,7 +59,8 @@ const App = () => (
);
```
+
On the server, tags are collected, and then on the client, server-generated tags are replaced with those rendered on the client side.
This process is important for maintaining the expected behavior, such as Single Page Applications (SPAs) when pages load that require changes to the head tags.
-However, you can manage asset insertion using `getAssets` from `solid-js/web`.
+However, you can manage asset insertion using `getAssets` from `solid-js/web`.
diff --git a/src/routes/solid-meta/reference/meta/base.mdx b/src/routes/solid-meta/reference/meta/base.mdx
index f0be6b9f92..5504efa927 100644
--- a/src/routes/solid-meta/reference/meta/base.mdx
+++ b/src/routes/solid-meta/reference/meta/base.mdx
@@ -6,7 +6,7 @@ order: 5
`Base` is a component that specifies the base URL for all relative URLs in the document.
This provides a way to define the [`base`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) element of your document's `head`.
-```tsx twoslash
+```tsx
import { Base } from "@solidjs/meta";
;
@@ -16,7 +16,7 @@ import { Base } from "@solidjs/meta";
### Adding `base` tag
-```tsx twoslash
+```tsx
import { MetaProvider, Base } from "@solidjs/meta";
export default function Root() {
@@ -26,4 +26,4 @@ export default function Root() {
);
}
-```
\ No newline at end of file
+```
diff --git a/src/routes/solid-meta/reference/meta/link.mdx b/src/routes/solid-meta/reference/meta/link.mdx
index e925f1dc94..4911462263 100644
--- a/src/routes/solid-meta/reference/meta/link.mdx
+++ b/src/routes/solid-meta/reference/meta/link.mdx
@@ -8,7 +8,7 @@ Commonly, this is used for linking stylesheets and other associations.
This component renders a [`link`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) element within the document's ``.
-```tsx twoslash
+```tsx
import { Link } from "@solidjs/meta";
;
```
@@ -19,7 +19,7 @@ import { Link } from "@solidjs/meta";
To add a favicon in an app, `` can be used to point to the asset:
-```tsx twoslash
+```tsx
import { MetaProvider, Link } from "@solidjs/meta";
export default function Root() {
diff --git a/src/routes/solid-meta/reference/meta/meta.mdx b/src/routes/solid-meta/reference/meta/meta.mdx
index 13e077da5d..3353a574b8 100644
--- a/src/routes/solid-meta/reference/meta/meta.mdx
+++ b/src/routes/solid-meta/reference/meta/meta.mdx
@@ -6,20 +6,20 @@ order: 3
The `` component represents metadata that cannot be represented by other HTML elements.
It is a wrapper for the native [`meta`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) element and has the same properties.
-```tsx twoslash
+```tsx
import { Meta } from "@solidjs/meta";
;
```
-
`Meta` components can be placed in the [`MetaProvider`](/solid-meta/reference/meta/metaprovider) or added throughout the application for additional metadata or override parents.
`Meta` tags are considered the same and will be overridden if `name` attributes match.
+
## Usage
### Adding `meta` tag
-```tsx twoslash {6-8}
+```tsx {6-8}
import { MetaProvider, Meta } from "@solidjs/meta";
export default function Root() {
@@ -31,4 +31,4 @@ export default function Root() {
);
}
-```
\ No newline at end of file
+```
diff --git a/src/routes/solid-meta/reference/meta/metaprovider.mdx b/src/routes/solid-meta/reference/meta/metaprovider.mdx
index d9932fa276..2be2f51a00 100644
--- a/src/routes/solid-meta/reference/meta/metaprovider.mdx
+++ b/src/routes/solid-meta/reference/meta/metaprovider.mdx
@@ -6,8 +6,8 @@ order: 6
`MetaProvider` is a parent component responsible for wrapping all the metadata components.
All components that are contained within this will be added to the application `
`
-```tsx twoslash
+```tsx
import { MetaProvider } from "@solidjs/meta";
// add meta components;
-```
\ No newline at end of file
+```
diff --git a/src/routes/solid-meta/reference/meta/style.mdx b/src/routes/solid-meta/reference/meta/style.mdx
index 4d049ab3e9..5cbd3ec661 100644
--- a/src/routes/solid-meta/reference/meta/style.mdx
+++ b/src/routes/solid-meta/reference/meta/style.mdx
@@ -5,7 +5,7 @@ order: 4
`Style` is a component that adds the [`style`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style) element to your document's `head`.
-```tsx twoslash
+```tsx
import { Style } from "@solidjs/meta";