Akita store in REACT app explain with code examples

 

Akita Store in React Application: Explanation with Code Examples

Akita is a state management library for JavaScript applications that helps in managing and organizing state in a clean, structured, and performant way. While Akita is often associated with Angular applications, it can be used in React as well.

In this tutorial, I’ll show you how to use Akita for state management in a React application, including setting up the store, defining entities, and updating the state.

1. Install Akita

First, we need to install Akita and its dependencies.

npm install @datorama/akita

Akita will automatically install its core package and provide the necessary functions for state management.

2. Setting Up the Akita Store

We will create a simple store to manage a list of todos. For this example, we will:

  • Define a Todo Store using Akita.
  • Create actions for adding and removing todos.
  • Use Akita's store and query to access and modify the state.

3. Creating the Todo Store and Service

3.1. Create the Store and Service

Create a store folder in the src directory and inside it, create the following files:

  1. todo.store.js – This will handle the state of our todos.
  2. todo.query.js – This will provide selectors to retrieve todos.
  3. todo.service.js – This will contain actions to modify the todos.

src/store/todo.store.js - This file defines the store:

import { createStore, Store } from '@datorama/akita'; // Define the initial state for the store export interface TodoState { todos: { id: number; text: string }[]; } // Define the initial state export const initialState: TodoState = { todos: [], }; // Create the store export class TodoStore extends Store<TodoState> { constructor() { super(initialState); } } // Create an instance of the TodoStore export const todoStore = new TodoStore();

src/store/todo.query.js - This file defines the query that provides access to the store’s data.

import { TodoStore } from './todo.store'; import { Query } from '@datorama/akita'; // Define the query to access the state export class TodoQuery extends Query { constructor(store: TodoStore) { super(store); } // Selector to get the list of todos getTodos() { return this.select('todos'); } } // Create an instance of TodoQuery export const todoQuery = new TodoQuery(todoStore);

src/store/todo.service.js - This file defines actions for adding and removing todos.

import { todoStore } from './todo.store'; import { todoQuery } from './todo.query'; // Action to add a todo export const addTodo = (text) => { const newTodo = { id: Date.now(), text }; // Unique ID based on timestamp todoStore.update((state) => ({ todos: [...state.todos, newTodo], })); }; // Action to remove a todo export const removeTodo = (id) => { todoStore.update((state) => ({ todos: state.todos.filter((todo) => todo.id !== id), })); };

4. Creating the React Components

Now we’ll create a simple React component that displays and allows interaction with the Todo store.

4.1. Todo List Component

src/components/TodoList.js - This component will show the todos and allow adding/removing them.

import React, { useState } from 'react'; import { addTodo, removeTodo } from '../store/todo.service'; import { todoQuery } from '../store/todo.query'; const TodoList = () => { // Local state to manage input text const [todoText, setTodoText] = useState(''); // Fetch todos using Akita's query const todos = todoQuery.getTodos(); // Handle adding a new todo const handleAddTodo = () => { if (todoText.trim()) { addTodo(todoText); setTodoText(''); } }; // Handle removing a todo const handleRemoveTodo = (id) => { removeTodo(id); }; return ( <div> <h2>Todo List</h2> <input type="text" value={todoText} onChange={(e) => setTodoText(e.target.value)} placeholder="Enter new todo" /> <button onClick={handleAddTodo}>Add Todo</button> <ul> {todos.value.todos.map((todo) => ( <li key={todo.id}> {todo.text} <button onClick={() => handleRemoveTodo(todo.id)}>Delete</button> </li> ))} </ul> </div> ); }; export default TodoList;

5. Rendering the Application

Finally, we’ll render the TodoList component in the App.js file.

src/App.js

import React from 'react'; import TodoList from './components/TodoList'; const App = () => { return ( <div className="App"> <h1>Akita Todo List</h1> <TodoList /> </div> ); }; export default App;

6. Running the Application

Now that everything is set up, run the application:

npm start

Visit http://localhost:3000 in your browser. You should see a simple todo list that allows you to:

  • Add new todos.
  • Remove existing todos.

Summary

In this example, we used Akita for state management in a React app. The key points in the Akita approach are:

  1. Store: This is where we define the state and how to modify it.
  2. Query: The query allows you to select specific parts of the store’s state.
  3. Service: This contains actions that update the state, such as adding or removing todos.
  4. React Integration: We used the Akita store and query inside React components, updating and displaying the state.

Advantages of Akita:

  1. Simplicity: Akita simplifies state management by providing a clean API for stores, queries, and actions.
  2. State Separation: It encourages the separation of state logic (store) from the view (React component).
  3. Immutable Updates: Akita ensures that state updates are always immutable.
  4. Ease of Integration: Akita works well with React (even though it’s popular in Angular) and integrates easily.

Akita provides a powerful and flexible tool for managing application state with minimal boilerplate. You can build scalable, maintainable, and easy-to-debug React applications using Akita as your state management solution.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics