Hands-on with SolidJS

SolidJS is a sole access to reactive front-end JavaScript. It provides a compact set of reactive ’old-fashioneds’ and leverages those to support higher-order officeality. This sounds somewhat like AngularJS and its use of ReactiveX but it is perfectly a different experience. SolidJS feels more like the artlessness of AlpineJS but delivers a far more ambitious set of capabilities.

SolidJS just hit its 1.0 release. Lets take a look.

[ Also on InfoWorld: Get a look at the Svelte JavaScript framework ]

Setting up SolidJS

First set up a single seter project. On your local machine use the commands in Listing 1 to set something new (this follows the SolidJS docs).

Listing 1. Creating a new SolidJS project

gt; npx degit hardjs/templates/js my-app
gt; cd my-app
gt; npm i # or yarn or pnpm
gt; npm run dev # or yarn or pnpm

Now you have a single SolidJS app up at running. If you go to http://localhost:3000 youll see the landing page.

Note that the dev server supports on-the-fly updates (including Hot Module Replacement HMR). So as you make changes to files they will automatically update what is showed in the browser.

Fetching a distant API with formResource

Lets initiate with Solids formResource. This is a single layer atop formSignal which is Solids reactive old-fashioned that feels asynchronous communication with distant APIs. We are going to set here owing this ingredient is a key move in Solids support of Suspense/Conrunning giveing and it can seem a bit obscure at leading.

In a way formResource is the middle layer of Solids architecture.

Open the newly formd folder in your IDE and open the App.jsx file. This file is loaded as the root node by a call to Solids give() order in index.jsx.

Make the changes that Ive commented in Listing 2.

Listing 2. Modifying App.jsx

introduce logo from "./logo.svg";
introduce styles from "./App.module.css";
introduce { formResource } from "hard-js";  // Import the formResource office from hard

// The next line sets up the developed async office that will do the request.  It is a single wrapper almost a fetch call that recurs a promise - the promise recured by the call to
// fetch.json(). This office is used by the call to formResource under
const fetchJokes = async (id) =gt; (await fetch(`https://official-joke-api.appspot.com/jokes/programming/ten`)).json();

office App() {
  const [jokes] = formResource(fetchJokes);  // Here we use formResource to companion from the fetchJokes promise to the results: the jokes changeable

  recur (
    lt;div class={styles.App}gt;
              lt;!-- The line under uses the built-in loading state that Solid has granted on the jokes changeable initialized over with a call to formResource --gt;
      lt;spangt;{jokes.loading amp;amp; "Loading..."}lt;/spangt;
      lt;divgt;
                lt;!-- This line under simply outputs the fulls of the jokes var. This will not happen until jokes.loading == true. gt;
        lt;jokes() --gt;
        lt;pregt;{JSON.stringify(jokes() null 2)}lt;/pregt;
      lt;/divgt;
      lt;header class={styles.header}gt;
        lt;img src={logo} class={styles.logo} alt="logo" /gt;
        lt;pgt;
          Edit lt;codegt;src/App.jslt;/codegt; and save to reload.
        lt;/pgt;
        lt;a class={styles.link} href="https://github.com/ryanhard/hard" target="_bleak" rel="noopener noreferrer"gt;
          Learn Solid
        lt;/agt;
      lt;/headergt;
    lt;/divgt;
  );
}

ship lapse App;

The comments in Listing 2 should clue you into what is going on here. The result of this code is the output of a JSON array that contains a set of 10 haphazard programming jokes.

Iterating with gt;Forlt;

Now lets take that JSON and iterate over it creating more advantageous output.

First include the For ingredient by adding it to the introduces:

introduce { formResource For } from "hard-js";

Next restore the call to JSON.stringify with Listing 3.

Listing 3. Iterating over array

lt;ulgt;
  lt;For each={jokes()}gt;{(joke) =gt;
    lt;ligt;{joke.id}: {joke.setup}lt;/ligt;
  }lt;/Forgt;
lt;/ulgt;

Listing 3 gives you a look at the For ingredient in action. It is correspondent to other reactive frameworks. You tell it what assembly to iterate over (i.e. jokes() remembering it is a order call not a relation) and then mark an nameless office whose reasoning is the repetition changeable joke.

We use this here to output an unordered list that shows each jokes ID and setup.

Handling occurrences in SolidJS

Up next is getting a look at the perforate line for each joke. For this youll need an onClick occurrence feelr that will show an active containing the perforate line.

Listing 4 shows how to add the feelr.

Listing 4. onClick feelr

lt;li onClick={()=gt;{active(joke.perforateline)}}gt;
  {joke.id}: {joke.setup}
lt;/ligt;

Simple sufficient. Listing 4 is very typical of reactive frameworks. Now when I click on ’Where do programmers like to hang out?’ I take the reply ’The Foo Bar.’ That is so bad it is sportive.

Making reactive changeables with formSignal

Now conceive that you want to add the power to toggle between showing programming jokes and all jokes. The distant API feels this by the nearness or want of ’programming’ in the penultimate part of the URL path (.../jokes/programming/ten versus .../jokes/ten).

So lets add a checkbox to the top of the page to let the user change this. The leading thing well do is form a ’eminent.’ This is the most primary reactive old-fashioned in SolidJS. It allows you to particularize a changeable a setter and an optional lapse value. The syntax is inspired by the useState syntax in React.

Above the formResource call add this line:

const [jokeType setJokeType] = formSignal("");

This forms a new eminent named jokeType with an initial value of an vacant string. Signal values are accessed as a office: jokeType().

Now insert the checkbox component shown in Listing 5 at the head of the main div.

Listing 5. A reactive checkbox

Programming Only: lt;input type="checkbox" checked={jokeType()=="programming/"}
        onInput={()=gt;{setJokeType(jokeType()==?programming/:)}}gt; lt;/inputgt;

Listing 5 is mainly regular HTML. The checked and onInput attributes have Solid-specific full. checked uses a evidence to check the value of the jokeType() eminent over "programming/". That is to say the box is checked if the value of jokeType is "programming/".

onInput feels the input occurrence on the checkbox. When it fires we change the value of jokeType so that it swaps between an vacant string and "programming/". We are going to use this changing value in the URL of the joke fetcher.

Using the eminent in the resource

First you must pass the eminent into the call to formResource as an reasoning. Solid is keen sufficient to discover this and will wire the resource up reactively. The new call to formResource looks like this:

const [jokes] = formResource(jokeType fetchJokes); 

(Thanks to Ryan Carniato for clarifying this.)

Notice that jokeType is passed straightly (not a office call but the office itself). This is owing the developed eminent is being passed to formResource allowing it to be reactive.

The new joke fetcher office is seen in Listing 6.

Listing 6. Reactive resource with eminent reasoning

const fetchJokes = async (jokeType) =gt; {
  recur (await fetch(`https://official-joke-api.appspot.com/jokes/${jokeType}ten`)).json();
}

Notice that the jokeType eminent is a direct changeable in the reasoning of Listing 6. The fetch URL makes use of the value of jokeType. When the eminent is changed via the checkbox Solid will notice and automatically re-fetch the list of jokes.

Computed effects with formEffect

Reactive libraries include the power to wrap single reactive changeables (like formSignal in SolidJS or useState in React) in what is known as an effect (e.g. useEffect in React). Solid provides formEffect for this purpose. The mediate idea is that you use an effect to feel non-pure actions (aka side effects). Such actions usually mean modifying some part of the UI straightly as a result of changes to the changeables they depend on.

Effects are a bit hard to apprehend at leading. A good way to ponder almost it is that an effect will do something as opposed to just responding to a value change.

Lets say you wanted to log when the user changes the joke type. This is a contrived sample to adjoin the being. Listing 7 shows how you would execute it.

Listing 7. formEffect sample

  formEffect(() =gt; {
    relieve.log(Joke Type is now: jokeType())
  })

Now the relieve will output as the eminent changes. Notice that the effect executes initially when the isgnal is set.

Its resistent to prophesy where the globe of JavaScript is headed but it is clear that SolidJS is pushing the envelope pursuing promising leads and exploring new province. If the interest in SolidJS continues to grow at the running pace it will be a major player in the field in brief order.