SolidJS - amark/gun GitHub Wiki

Introduction

Welcome to GunDB Solid-JS developer! So you want to use GunDB with Solid-JS? No problem, lets get into it. So by you showing up here and wanting to use GunDB with Solid-JS, I can assume that you know that Solid-JS is solid. This is good, because this means that developing interfaces with jsx without the virtual-dom is going to be great and plus, we can tie it in with GunDB to create a real-time to-do app.

Installation

First we need to install a solid-js template, we can do so with the following:

> npx degit solidjs/templates/js my-app
> cd my-app
> npm i # or yarn or pnpm
> npm run dev # or yarn or pnpm

Now we need to install GunDB, enter the following into your terminal:

npm i -S gun # or yarn or pnpm

Database

Now we need to initialize our to-do's database, for this example, this will be located at src/state/database.js

import Gun from 'gun/gun';

let database = new Gun({ peers: ['https://gun-manhattan.herokuapp.com/gun'] }); // This peer is optional, you can use your own if you want.

export { database };

App

Once we have initialized, we can create our To-Do's component in src/App.jsx, make sure to import our database from src/state/database.js or else we won't be able to create our to-do's with GunDB.

import { render } from "solid-js/web";
import { onMount, createEffect, createSignal } from "solid-js";
import { createStore } from "solid-js/store";
import { database } from './state/database.js';

let App = () => {
  let [state, setState] = createStore<any>({
    todos: [],
    todoText: undefined,
  });

  onMount(() => {
    database
      .get("solidToDos")
      .map((todo, key) => state.todos.concat({...JSON.parse(todo), key}));
  });

  let addToDo = () => {
    database
      .get("solidToDos")
      .set(JSON.stringify({ text: state.todoText.value, completed: false }));
  };

  let setCompleted = (key) => {
    let todo = state.todos.filter((todo) => todo.key === key)[0];

    database.get("solidToDos").get(key).put(JSON.stringify({...todo, completed: true }));
  }

  return (
    <div>
      <div>ToDos</div>
      <div>
        <input
          placeholder="type something to-do"
          onKeyUp={({ target }) => {
            setState({
              ...state,
              todoText: target,
            });
          }}
        />
        <button onClick={() => addToDo()}>Add</button>
      </div>

      <div>
        {state.todos.map(({ text, completed, key }) => (
          <div id={`todo-${key}`} style={{ "text-decoration": completed && "line-through" }} onClick={() => setCompleted(key)}>{text}</div>
        ))}
      </div>
    </div>
  );
};
render(() => <App />, document.getElementById("app"));
⚠️ **GitHub.com Fallback** ⚠️