DEV Community

Pedro Correia
Pedro Correia

Posted on

I had to create a Guest Mode mechanism in React

Introducing

As usual, in all my previous projects it's very common to use some auth provider to do the authentication mechanism, but this case would be different, besides the usual case of using an auth provider, I would create a guest mode mechanism.

My Use Case

It's a project where users can manage their project, it's a simple CRUD.
The thing is, if you are a registered user you can save as many projects as you want in the app, however as a guest user the criteria acceptance is a bit different, as a guest user you can only save 1 project.. Just to let you know, there's a size limit to be saved, but it depends on some variables, like: browser and disk space.
If you want to know this limit, use the method from Storage API navigator.storage.estimate()

What solution did I apply?

I choose indexedDB to save all guest users data in the browser, and I counted with Dexie(https://dexie.org/docs/Tutorial/React) to help me.

As the project creation for the logged in users was done, I already knew all the properties I'd need for the guest users. I'll explain how I solved this challenge step by step.

Step 1: Installing dexie
yarn
yarn add dexie
yarn add dexie-react-hooks

npm
npm install dexie
npm install dexie-react-hooks

Step 2: I've created an interface with all needed properties to be used on Project Creation.

IProject.ts

Step 3: I created a hook to initialise the Dexie context, which contains the database and schema creation.

db.ts

Step 4: Let's create a form to create our project, including the addProject function to perform the operation through the db context.

ProjectForm.tsx

Step 5: Let's create a List component to show all projects that have been created and perform the useLiveQuery function through the db context.

ProjectList.tsx

Step 6: And finally, after adding a project, you can see in the application tab on browser settings, indexedDB and ProjectDB, all projects that is listed, for sure you can close and open the browser all data is persisted until you clear the DB.

Example

I hope you can use it to manage your guest users as well, and if you want to play with this demo, follow the codesandbox bellow.

https://codesandbox.io/p/sandbox/react-typescript-forked-pfpdz8?workspaceId=51e2f20f-c72d-466e-8e65-35cf50be13d0

Top comments (0)