Project in Zustand

EthanEthan
2 min read

Expense Tracker

We will be making an expense tracker project , to get a stronghold on Zustand.
Project includes , description of expense , amount , add button , and list view of total expenses and total expense done.

Initialize the Project.

  1. initialize a project using npm create vite@latest ,

  2. Add Tailwind configuration โ†’ Tailwind + vite setup

  3. npm i zustand then npm run dev ,& your template is ready.

Initialize zustand

  1. import create from zustand.

  2. we will make custom hook useStore , using zustand. (make interface for it )

  3. useStore will have -

    1. expenses array to store all the expenses, it contains i**d , description and amount. (make interface for it too )

    2. function to add expense in array.

    3. function to remove expense using expense id

  • set function is used to update the state

โ†’ This will look like this , inside the src/store.ts file

import {create} from 'zustand';
// Interface for array
interface Expense {
    id: number;
    description: string;
    amount : number;
}
// Interface for useStore
interface ExpenseStore {
   expenses: Expense[];
   addExpense: (expense: Expense)=> void;
   removeExpense: (id: number)=> void;

}

export const useStore = create<ExpenseStore>((set=>({
    expenses : [],

    addExpense: (expense)=>
        set((state) => ({
            expenses: [...state.expenses, expense]
        })),

    removeExpense: (id) => 
        set((state)=>({
            expenses: state.expenses.filter((expense)=> expense.id !== id),
        }))
})))

Make UI for it.

  1. Inside src , make components/ExpenseTracker.tsx, which ill make components folder with file ExpenseTracker.tsx inside it.

  2. As per your styling , make two inputs boxes ,to take description as input and amount as input,

  3. Then add a button, which will take that input values and store them in array ( we created in store.ts file) , for id we can use Date.now() function.

  4. Below this , use list tag, to display all the expense with descriptions and delete button aside of each expense. (this delete button will utilize the removeExpense function we created previously ).

  5. Finally, display the total amount of expenses , this can be done using reduce() method on array.

โ†’ This is how it will look - > copy the code from github ExpenseTracker.tsx

Congratss!!! you have made a project using zustand. ๐Ÿ‘ โ™ฅ

0
Subscribe to my newsletter

Read articles from Ethan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ethan
Ethan

Just another coder, tryin to center div