import { createStore } from "solid-js/store";
class StoreSingleton {
// Private static instance
static #instance;
// Private constructor to prevent direct instantiation
constructor() {
if (StoreSingleton.#instance) {
throw new Error(
"Use StoreSingleton.getInstance() to get an instance of this class.",
);
}
// Initialize the Solid.js store with default state
this.state = createStore({
user: null,
todos: [],
});
}
// Public static method to get the singleton instance
static getInstance() {
if (!StoreSingleton.#instance) {
StoreSingleton.#instance = new StoreSingleton();
}
return StoreSingleton.#instance;
}
// Getter for accessing the Solid store
getState() {
return this.state[0];
}
// Methods to update the state
setUser(user) {
this.state[1]({ user });
}
addTodo(todo) {
this.state[1]("todos", (todos) => [...todos, todo]);
}
removeTodo(index) {
this.state[1]("todos", (todos) => todos.filter((_, i) => i !== index));
}
}
// Usage
const store = StoreSingleton.getInstance();
store.setUser({ id: 1, name: "John Doe" });
store.addTodo({ id: 1, text: "Learn Solid.js", completed: false });
store.addTodo({ id: 2, text: "Build a project", completed: false });
console.log(store.getState());
// Output:
// {
// user: { id: 1, name: "John Doe" },
// todos: [
// { id: 1, text: "Learn Solid.js", completed: false },
// { id: 2, text: "Build a project", completed: false }
// ]
// }
const sameStore = StoreSingleton.getInstance();
sameStore.removeTodo(0);
console.log(sameStore.getState());
// Output:
// {
// user: { id: 1, name: "John Doe" },
// todos: [
// { id: 2, text: "Build a project", completed: false }
// ]
// }