New Self New Life
No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
New Self New Life
No Result
View All Result
Home Softwares

How to use indexedDB (Dexie) in NextJs

by admin
2 years ago
in Softwares
How to use indexedDB (Dexie) in NextJs
Share on FacebookShare on Twitter


IndexedDB is a low-level API in net browsers that gives to retailer, retrieve, and carry out transactions on giant quantities of NoSQL information within the shopper’s browser.

It’s designed for net purposes that must work offline or require giant quantities of knowledge to be saved regionally.

What’s dexie ?

Dexie is a JavaScript library that gives a higher-level API for working with IndexedDB. It simplifies the method of interacting with IndexedDB by offering a extra intuitive and developer-friendly interface.

Dexie handles duties resembling opening and upgrading databases, creating and managing object shops, and performing transactions.

Listed here are some key options of Dexie:

Promise-Primarily based API: Dexie makes use of Guarantees, which makes it simpler to work with asynchronous operations.

Simplified Syntax: It gives a clear and easy-to-use syntax for frequent operations like creating, studying, updating, and deleting information.

Computerized Schema Upgrades: Dexie helps handle schema variations and might routinely improve your database while you make modifications to your information construction.

Querying and Filtering: It contains strategies for querying the information in your database, permitting you to filter and retrieve particular information.

Transactions: Dexie abstracts transactions, making it simpler to work with the IndexedDB transaction mannequin.
Help for Complicated Knowledge Varieties: Dexie can retailer extra complicated information sorts like arrays and objects.

Cross-Browser Compatibility: It gives a constant API throughout totally different browsers, dealing with any browser-specific quirks or inconsistencies.

Offline Help:  Dexie gives offline help, which is especially helpful for constructing Progressive Net Apps (PWAs) or purposes that must operate offline. It permits you to retailer information regionally and synchronize it with a server later.

Let’s see the implementation  –

Step 1: Create a Subsequent.js Mission
In step one, let’s create a Subsequent.js venture and arrange the create, replace, and delete operation utilizing dexie library of IndexedDB.

To arrange the subsequent js venture You may observe this setup nextjs venture weblog that covers all in regards to the subsequent js venture setup.

Now our subsequent app title is “ next-dexie-implementation “. As soon as the venture is created, navigate into the venture listing by working:

cd next-dexie-implementation

Step 2: Set up Dependencies
We’d set up the required dependencies for working with dexie in our Subsequent.js venture. Run the next command in your terminal:

npm set up dexie  // dexie
npm set up dexie-react-hooks // dexie hook

Our venture – construction appear to be as talked about under

project-structure

Step 3: DB mannequin 
After that we’ll make db folder within the root listing underneath it we create the db.mannequin.ts file.

import Dexie, { Desk } from 'dexie';

// desk inteface
export interface Pupil {
  id?: quantity;
  title: string;
  rollNumber: quantity;
}

export class DB extends Dexie {
// desk title is scholar 
  college students!: Desk<Pupil>; 
  constructor() {
    tremendous('myDatabase');
    this.model(1).shops({
      college students: '++id, title, rollNumber'  
    });
  }
}

export const db = new DB(); // export the db

college students is our desk title wherein ‘ve title and rollNumber key and first key with id title

After initializing the college students desk we’ve exported it as DB under in order that each time we’ll must entry this DB we will entry it.

Step 4: Create, replace, and delete operations with college students desk 
As we earlier mentioned make create, replace, and delete operations with scholar desk information and there are three fields as you will have seen in college students that was title, rollNumber, and final is the first key id.

To carry out create, replace, and delete operations we’ve created a parts listing within the root folder underneath it we’ve created StudentMngmt.tsx and this file accommodates these code snippets.

import React, { FC } from "react";
import { db } from "@/db/db.mannequin";
import { useLiveQuery } from "dexie-react-hooks";
const StudentMngmt: FC = () => {
  const [students, setStudents] = React.useState({ title: '', rollNumber: '', id: null });
  // dexie hook to get dwell information 
  const studentList = useLiveQuery(() => db.college students.toArray());

  // add scholar 
  const addStudent = React.useCallback(async () => {
    if (college students?.title && college students?.rollNumber) {
      await db.college students.add({
        title: college students?.title,
        rollNumber: Quantity(college students?.rollNumber)
      });
      setStudents({ title: '', rollNumber: '', id: null });
    }
  }, [students])

  // replace scholar 
  const updateStudent = React.useCallback(async () => {
    if (college students?.id && college students?.title && college students?.rollNumber) {
      await db.college students.put({
        id: college students?.id,
        title: college students?.title,
        rollNumber: Quantity(college students?.rollNumber)
      });
      setStudents({ title: '', rollNumber: '', id: null });
    }
  }, [students])

  // delete scholar 
  const deleteStudent = React.useCallback(async (id: any) => {
    await db.college students.delete(id);
  }, [])

  // Pupil record Part
  const StudentList = () => {
    return (
      <div className="">
        <desk >
          <tr>

            <th>ID</th>
            <th>NAME</th>
            <th>ROLL NUMBER </th>
            <th>DELETE   </th>
            <th>UPDATE  </th>
          </tr>
          {
            studentList?.map((i: any, index: quantity) => {
              return (
                <tr key={index}>
                  <td type={{ paddingTop: '10px' }} ><span type={{ paddingLeft: '10px', paddingRight: '10px' }}>{i.id}</span></td>
                  <td type={{ paddingTop: '10px' }} ><span type={{ paddingLeft: '10px', paddingRight: '10px' }}>{i.title}</span></td>
                  <td type={{ paddingTop: '10px' }} > <span type={{ paddingLeft: '10px', paddingRight: '10px' }}>{i.rollNumber}</span></td>
                  <td type={{ paddingTop: '10px' }} > <button onClick={addStudent} type={{ paddingLeft: '10px', paddingRight: '10px', marginLeft: '10px' }} onClickCapture={() => deleteStudent(i.id)}>DELETE</button></td>
                  <td type={{ paddingTop: '10px' }} ><button onClick={() => setStudents({ ...i })} type={{ paddingLeft: '10px', paddingRight: '10px', marginLeft: '10px' }}>UPDATE</button></td>
                </tr>
              )
            })
          }
        </desk>
      </div>)
  }

  // Add and Replace Type Part 
  return (
    <div>
      <div type={{ paddingLeft: '30px' }} >
        <h2 type={{ marginBottom: '20px', marginTop: '20px' }}>{college students?.id ? 'Replace' : 'Add'} Pupil </h2>
        <div >
          <label htmlFor="Identify" type={{ paddingRight: '10px' }}>Identify</label>
          <enter sort="textual content" worth={college students?.title} onChange={(e) => setStudents({ ...college students, title: e.goal.worth })} placeholder="Identify" title="Identify" type={{ marginRight: '30px' }} />
          <label htmlFor="roll" type={{ paddingRight: '10px' }}>Roll Quantity </label>
          <enter sort="quantity" worth={college students?.rollNumber} onChange={(e) => setStudents({ ...college students, rollNumber: e.goal.worth })} placeholder="Roll Quantity" title="rollNumber" />
          {
            college students?.id ? (
              <button onClick={updateStudent} type={{ paddingLeft: '10px', paddingRight: '10px', marginLeft: '10px' }}>SUBMIT</button>
            ) : (
              <button onClick={addStudent} type={{ paddingLeft: '10px', paddingRight: '10px', marginLeft: '10px' }}>ADD</button>
            )
          }
        </div>
        <h2 type={{ marginBottom: '20px', marginTop: '20px' }}>Pupil Listing</h2>
        <div><StudentList /></div>
      </div>
    </div>
  );
}
export default StudentMngmt

Now let’s demystify StudentMngmt.tsx code snippet, right here db is our indexdDB database exported from db.mannequin.ts wherein we’ve created college students desk after that now we have additionally

import { db } from "@/db/db.mannequin";
import { useLiveQuery } from "dexie-react-hooks";

imported useLiveQuery that could be a hook that gives dwell Question information from the desk means when you’ve got added or up to date the brand new information in college students desk or any desk you don’t must name the operate or technique time and again to get up to date information.

  const studentList = useLiveQuery(() => db.college students.toArray());

Right here studentList is scholar desk information in array format which we’ve mapped in our StudentList element.

And in addStudent the operate we’re utilizing db.scholar.add({title:title , rollNumber:rollNumber})

likewise in updateStudent operate, we’re utilizing db.scholar.put({ id:id , title:title , rollNumber:rollNumber}) want to note that this replace dexie API takes an additional key that’s id , mainly on the idea of it’ll discover out the actual desk information and replace these information.

Now our final operate associated to dexie operation is deleteStudent this dexie API db.scholar.delete(id) simply takes id to carry out deletion.

dexie_webkul-1

Step 5: Importing into Route web page :
At this second we’re simply on the curve towards end so in our final step, import StudentMngmt.tsx element into the route web page right here we’ve imported it into index.tsx however it’s your want wherein web page you wish to import. so the ultimate end result you may see under.

 Conclusion: Integrating the Dexie library right into a Subsequent.js software gives a robust client-side database answer. Dexie simplifies the method of managing information on the shopper aspect, permitting for environment friendly storage and retrieval operations. By leveraging Dixie’s intuitive API and seamless

Integration with Subsequent.js, builders can create dynamic and responsive net purposes with sturdy offline capabilities.

Begin your Headless Growth with Webkul.
Blissful Coding !!

author-thumb

Abhijeet Kumar
2 Badges

2 November 2023



Source link

Tags: DexieindexedDBNextjs
Previous Post

The Birdsong Society at Merriweather Lakehouse Hotel

Next Post

Immerse Yourself in the Dreamlike Drum & Bass of What So Not and Daktyl's "Fever"

Related Posts

Vivaldi 7.4 RC 3 – Vivaldi Desktop Browser snapshot 3684.34/35
Softwares

Vivaldi 7.4 RC 3 – Vivaldi Desktop Browser snapshot 3684.34/35

by admin
May 16, 2025
User Guide For Recipe App For Wix
Softwares

User Guide For Recipe App For Wix

by admin
May 13, 2025
Software update keeps Newark airport radar online but network concerns and flight limits remain
Softwares

Software update keeps Newark airport radar online but network concerns and flight limits remain

by admin
May 14, 2025
10+ Best Free Hero Scene Mockup Templates for Photoshop in 2025 — Speckyboy
Softwares

10+ Best Free Hero Scene Mockup Templates for Photoshop in 2025 — Speckyboy

by admin
May 15, 2025
AI updates from the past week: IBM watsonx Orchestrate updates, web search in Anthropic API, and more — May 9, 2025
Softwares

AI updates from the past week: IBM watsonx Orchestrate updates, web search in Anthropic API, and more — May 9, 2025

by admin
May 11, 2025
Next Post
Immerse Yourself in the Dreamlike Drum & Bass of What So Not and Daktyl's "Fever"

Immerse Yourself in the Dreamlike Drum & Bass of What So Not and Daktyl's "Fever"

A wider look at life

Best instant cameras 2023

  • Trending
  • Comments
  • Latest
Cameron Monaghan Discusses Erotic Thriller

Cameron Monaghan Discusses Erotic Thriller

January 13, 2022
Fundamental New Google Photos Features Should Have Been There From The Start

Fundamental New Google Photos Features Should Have Been There From The Start

April 26, 2021
Most Useful Gadgets in 2021 – Nogentech.org

Most Useful Gadgets in 2021 – Nogentech.org

July 29, 2021
Guide for Odoo Website Razorpay Checkout Payment Acquirer

Guide for Odoo Website Razorpay Checkout Payment Acquirer

January 6, 2023
UGREEN 65W USB Charger and Power Adapter review 

UGREEN 65W USB Charger and Power Adapter review 

January 25, 2023
User Manual of Intercom Odoo Connector

User Manual of Intercom Odoo Connector

April 11, 2023
User Guide for Odoo Saas Bridge For Magento 2

User Guide for Odoo Saas Bridge For Magento 2

February 15, 2023
Top 8 Buy Now, Pay Later (BNPL) Services For Businesses

Top 8 Buy Now, Pay Later (BNPL) Services For Businesses

October 22, 2023
Cable giants Cox and Charter agree to $34 billion merger

Cable giants Cox and Charter agree to $34 billion merger

May 16, 2025
Frugal Friday’s Workwear Report: Stripe Rib Polo Sweater

Frugal Friday’s Workwear Report: Stripe Rib Polo Sweater

May 16, 2025
Vivaldi 7.4 RC 3 – Vivaldi Desktop Browser snapshot 3684.34/35

Vivaldi 7.4 RC 3 – Vivaldi Desktop Browser snapshot 3684.34/35

May 16, 2025
Celebrity court cases: The most popular celebrity court appearances, trials, and lawsuits that got the world talking, including Kim Kardashian, Johnny Depp and Amber Heard, Blake Lively and Justin Baldoni, and more | In Pictures

Celebrity court cases: The most popular celebrity court appearances, trials, and lawsuits that got the world talking, including Kim Kardashian, Johnny Depp and Amber Heard, Blake Lively and Justin Baldoni, and more | In Pictures

May 16, 2025
Instagram Shares Advice on Switching Your Content Focus in the App

Instagram Shares Advice on Switching Your Content Focus in the App

May 16, 2025
Chris Brown & Rihanna’s Relationship Timeline – Hollywood Life

Chris Brown & Rihanna’s Relationship Timeline – Hollywood Life

May 16, 2025
Hoda Kotb Reveals Post-Today Routine & Why Her 50s Were Her Favorite Decade

Hoda Kotb Reveals Post-Today Routine & Why Her 50s Were Her Favorite Decade

May 16, 2025
Falcon Finance Surpasses $350 Million in USDf Circulating Supply

Falcon Finance Surpasses $350 Million in USDf Circulating Supply

May 15, 2025
New Self New Life

Your source for entertainment news, celebrities, celebrity news, and Music, Cinema, Digital Lifestyle and Social Media and More !

Categories

  • Celebrity
  • Cinema
  • Devices
  • Digital Lifestyle
  • Entertainment
  • Music
  • Social Media
  • Softwares
  • Uncategorized

Recent Posts

  • Cable giants Cox and Charter agree to $34 billion merger
  • Frugal Friday’s Workwear Report: Stripe Rib Polo Sweater
  • Vivaldi 7.4 RC 3 – Vivaldi Desktop Browser snapshot 3684.34/35
  • Home
  • Disclaimer
  • DMCA
  • Privacy Policy
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites. slotsfree  creator solana token

No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites.

ph betting site