DEV Community

loading...
Cover image for Integrating Fauna Into Preact WMR Application

Integrating Fauna Into Preact WMR Application

17th_streetCode
Software Developer. UI/UX Designer occasionally. Travels alot. Music 🤝🏾 Headphones.
・6 min read

In this tutorial, we’ll integrate Fauna into a Preact WMR application. We’ll perform CRUD actions to our database within the WMR application. Our focus will solely be on exploring Fauna CRUD actions within a Preact WMR application.

While the development process is evolving for developers, there’s a need by many developers to have an all-in-one development tool that will make web application development faster and easier. WMR gives developers the added feature and advantage of building web applications based on the all-in-one development tool.

In this tutorial, we will integrate Fauna into a Notes keeping application built using Preact WMR library. Let’s start by implementing the frontend part of the Notes application.

Prerequisites

  • A basic understanding of React and React hooks.
  • Have Node installed on our local machine
  • A basic understanding of JavaScript
  • Have yarn or npm installed as a node package manager

Implementing The Frontend Application

We will implement the frontend part of the application by cloning a WMR project, and walk through the different parts of the project. We start by cloning an already built WMR application repository.

git clone https://github.com/IkehAkinyemi/preact-wmr-notes-app.git
Enter fullscreen mode Exit fullscreen mode

Once done cloning the application, open the project in your choice of text editor. Within the project, our focus is on the ./public/api and ./public/config folders. Within these folders, we have our setup and connection to our database, that we’ll set up later within this tutorial.

Next, we install Fauna’s JavaScript driver, this will help make CRUD actions to the database for fetching, deleting and also creating data on it.

yarn add faunadb
Enter fullscreen mode Exit fullscreen mode

or

npm install --save faunadb
Enter fullscreen mode Exit fullscreen mode

Within the ./public/config folder, we create a db.js file, and import the Fauna library. We proceed to set up our client and query variables to help us connect to our database.

import faunadb from "faunadb";
const client = new faunadb.Client({ secret: process.env.REACT_APP_DB_KEY });
const q = faunadb.query;
export { client, q };
Enter fullscreen mode Exit fullscreen mode

We will generate our API key once we have our database set up later within this tutorial. Let’s proceed to define our CRUD actions within the ./public/api/index.js file.

import { client, q } from "../config/db";
const getAllNotes = client
  .query(q.Paginate(q.Match(q.Ref("indexes/all_notes"))))
  .then((res) => {
    const noteRef = res.data;
    const getAllDataQuery = noteRef.map((ref) => {
      return q.Get(ref);
    });
    return client.query(getAllDataQuery).then((data) => data);
  })
  .catch((err) => err.message);
const createNote = (note) =>
  client
    .query(q.Create(q.Collection("notes"), { data: { note } }))
    .then((ref) => ref)
    .catch((err) => err.message);
const deleteNote = (noteId) =>
  client
    .query(q.Delete(q.Ref(q.Collection("notes"), noteId)))
    .then((ref) => ref)
    .catch((err) => err.message);
export { getAllNotes, createNote, deleteNote };
Enter fullscreen mode Exit fullscreen mode

Here we created and exported three different CRUD actions: getAllNotes, createNote, and deleteNote. These will help us develop, obtain, and delete our Notes data from the database through some frontend actions that we will see later in the tutorial. Within the getAllNotes action, our database set up would contain Indexes with the name of all_notes. This will help us group our note data, within the database, into a single group search. The createNote action records that our database would contain a Collection named notes.

We proceed to the ./public/pages/app/index.jsx file where we created JSX elements that will help us markup and style our frontend application. And then import all our API functions to help us carry out our CRUD actions. We also define utility functions that will work with React hooks to get all the notes data from the database, create note data on the database, and delete a particular Note.

import { useState, useEffect } from "preact/hooks";
import { FaTrash } from "react-icons/fa";
import { createNote, deleteNote, getAllNotes } from "../../api";
import styles from "./style.module.css";

export default function NoteApp() {
  const [Notes, setNotes] = useState([]);
  useEffect(() => {
    getAllNotes.then((res) => {
      setNote(res);
      console.log(res);
    });
  }, []);
  const [currNote, setcurrNote] = useState("");
  const addNote = (e, note_content) => {
    Notes.push({
      id: Notes.length,
      note: note_content,
    });
    // createNote(note_content).then((res) => {
    //   console.log("Expense details added to the database");
    // });
    setcurrNote("");
    e.preventDefault();
  };
  const deleteNoteItem = (note_idx) => {
    const notes = Notes.filter((note) => note.id !== note_idx);
    setNotes(notes);
    deleteNote(note_idx).then((res) => res);
  };
  const extractNotes = () =>
    Object.values(Notes).map((note) => (
      <li key={note.id} class={styles.noteItem}>
        <span
          class={styles.deleteIcon}
          onClick={(e) => deleteNoteItem(note.id)}
        >
          <FaTrash size={20} color={"red"} />
        </span>
        {note.note}
      </li>
    ));
  return (
    <section class={styles.wmr_app}>
      <h1>Preact WMR Note Application Built With Fauna</h1>
      <div class={styles.inputArea}>
        <h3>Write and add your Notes.</h3>
        <input
          class={styles.inputField}
          type="text"
          value={currNote}
          onChange={(e) => setcurrNote(e.currentTarget.value)}
          onKeyUp={(e) => (e.key == "Enter" ? addNote(currNote) : null)}
        />
        <button class={styles.button} onClick={(e) => addNote(e, currNote)}>
          Add
        </button>
      </div>
      <div class={styles.notes_list_wrapper}>
        <ul class={styles.unstyled_list}>{extractNotes()}</ul>
      </div>
    </section>
  );
}

Enter fullscreen mode Exit fullscreen mode

In the above code, we define utility functions, addNote, deleteNoteItem and extractNotes. The addNote will be used to update our database with the new note item and update our frontend application. The deleteNoteItem would be used to delete note items from the database, and also on the frontend part of the application. The extractNote will help us extract the values of the notes we will get from the database. Our frontend application will look like the below UI with the predefined styles we have in the ./public/pages/app/styles.module.css:

first photo

Now we have the frontend part of our application ready. Now, let’s integrate Fauna into our application.

Integrating Fauna Into Our Application

Fauna is a flexible, developer-friendly, transactional cloud database delivered as a secure Data API that provides two interfaces: GraphQL and the Fauna Query Language (FQL). It includes functionality to store collections, indexes, and other databases (multi-tenancy). To learn more about Fauna, visit the official documentation.

We need to create the database for our Preact WMR application in Fauna’s dashboard. If you have not created an account on Fauna before now, create one here.

Within the dashboard screen, press on the NEW DATABASE button, and provide a name for the database then press the SAVE button. In this tutoria,l we call it notes_application.

Navigation

Next, we create a Fauna collection to store data in the recently created database. A Collection is similar to SQL tables containing similar characteristics, e.g. a user collection with information about users in the database. Click on the NEW COLLECTION.

Fauna's dashboard

Once we click on the button, it will take us to a form where we’ll name our data collection. In this tutorial, we’ll call it notes:

collection

Next we create the INDEXES for the collection of the database. A Fauna index allows us to browse through data stored in a database collection based on specific attributes.

collection form

We’ll click on the NEW INDEX to create a new index for our database. We name ours all_notes. Remember to select the current collection we’re creating the index for.

index

Next navigate to the SECURITY tab. By clicking on the SECURITY button on the sidebar to generate an API key for our application. Click the SAVE button.

security

Once you have done this, Fauna will present you with your Secret Key. Copy the key immediately and store it within our application or somewhere easily retrievable because it will only be displayed once.

Now we’re done with the basic setup for our database. We can now go to our application and start creating, storing, getting, and deleting our notes.

Our final frontend application will look like the UI below. The frontend application is ready to carry out our basic CRUD actions.

complete application

Our database will contain this data in an object with a note field.

database

Conclusion

In this tutorial, we built a Notes application with Fauna's serverless database and Preact WMR. We saw how easy it is to integrate Fauna into a Preact WMR application and got the chance to explore some of its core features and functionalities. Here’s my Twitter handle, @ikehakinyemi , also my dev.to handle, I would love to answer your questions on this tutorial and also see you build with Fauna.

The source code of this tutorial is available on GitHub.

Discussion (0)