Updating a state to display updated data
Unanswered
Pond loach posted this in #help-forum
Pond loachOP
I am creating a forums system. I dont care about live updates other than when the user creates a thread. I have it so it gets all the threads, then map them, and display them. However, after creating a thread, it gets added to the database, but not the state. How would I add a object to an array using zustand.
Current setup:
console.log(state); returns
```
Any help is appreciated!
Current setup:
const useThreadsStore = create<ThreadsState>()(
persist(
(set) => ({
threads: [],
addThread: (thread) => {
set((state) => {
console.log(state);
return {
threads: [...state.threads.data, thread],
};
});
},
}),
{
name: "threads-storage",
}
)
);console.log(state); returns
:
data
:
Array(2)
0
:
{_id: '663fbb99581efeefbaf3a937', category: 'announcements', title: 'dssadasd', content: '<p>dasadsasd</p>', author: 'Velvet', …}
1
:
{_id: '663fbc47581efeefbaf3a93c', category: 'announcements', title: 'dsaasdads', content: '<p>dasasddas</p>', author: 'Velvet', …}This is how I access the state: const threads = useThreadsStore((state: any) => state.threads);When I do this, I get this error:TypeError: Cannot read properties of undefined (reading 'map')It occurs here: ``` return (
<div>
<div>
<ForumPostCreator category={slug} author={"Velvet"} />
</div>
{threads.data.map((thread: any) => (
<div
key={thread._id}
onClick={() => handleClick(thread.id)}
className="hover:cursor-pointer "
>
{thread.title}
</div>
))}
</div>
);```
Any help is appreciated!
5 Replies
Pond loachOP
Is there better way of accomplishing what I am looking for?
Pond loachOP
Still looking for a fix. Any help is appreciated
Pond loachOP
Bump
please only bump at most once a day
@joulev please only bump at most once a day
Pond loachOP
Sorry