I am new to react and states. I am trying to use Zustand to manage my global states. I created a store where I have three function, fetchTodos, where I fetch my data from a Json file (my data is an array of objects, id, title and completed). The second function is called handleAddItem, where I am trying to update the state of my array so I can add a new item to said array. The third function is handleToggleCompleted, this function helps me toggle a checkbox field depending on the value of completed. The error I am getting is "set.getState is not a function" whenever I try to add a new item.
I would appreciate the help or pointing me to the right docs to read.
This is my code for my store:
import {create} from 'zustand';
const useTodoStore = create((set) => ({
toDoList: [],
newItem: '', // Input value for new item
// Fetch data
fetchTodos: async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos');
const todos = await response.json();
set({ toDoList: todos });
} catch (error) {
console.error('Error fetching todos:', error);
}
},
// Actions for updating state
handleAddItem: (title) => {
title.preventDefault();
const newId = Math.max(...set.getState().toDoList.map((todo) => todo.id)) + 1;
const newTodoItem = { id: newId, title, completed: false };
set({ toDoList: [...set.getState().toDoList, newTodoItem], newItem: '' });
},
handleToggleCompleted: (id) =>
set((state) => ({
toDoList: state.toDoList.map((todo) =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
),
})),
setNewItem: (value) => set({ newItem: value }),
}));
export default useTodoStore;
You have to use get().item in case of fetching state instead of set.getState().item
Here is an article for reference: https://medium.com/globant/react-state-management-b0c81e0cbbf3