Replies: 2 comments
-
I am aware I could just nest the observables in one class but my real world app has a screen to edit hobbies and it simplifies it if it's a separate class, there is also a lot of other functionality in the class |
Beta Was this translation helpful? Give feedback.
0 replies
-
I don't think it's because it's a class because the same thing happens if I do this import { Observable, observable, ObservablePrimitive } from "@legendapp/state";
import { For, use$, useObservable } from "@legendapp/state/react";
import { $React } from "@legendapp/state/react-web";
interface InfoType {
firstName: string;
lastName: string;
hobbies: Observable<HobbyType>[];
}
interface HobbyType {
name: string;
description: string;
}
function createInfoStore() {
return observable<InfoType>({
firstName: "",
lastName: "",
hobbies: [],
});
}
interface HobbyType {
name: string;
description: string;
}
const store = createInfoStore();
store.hobbies.push(
observable({ name: "Hobby 1", description: "Description 1" }),
observable({ name: "Hobby 2", description: "Description 2" }),
observable({ name: "Hobby 3", description: "Description 3" })
);
export function Test() {
const selectedHobbyIndex = useObservable<number | null>(null);
const selectedHobby = use$(() => {
const index = selectedHobbyIndex.get();
if (index === null) return null;
console.log(store.hobbies[index].get());
return store.hobbies[index];
});
return (
<div className="max-w-xl mx-auto mt-12">
<div className="flex items-center justify-center gap-x-2">
<Input item={store.firstName} />
<Input item={store.lastName} />
</div>
<hr className="my-3" />
<For each={store.hobbies}>
{(item, index) => {
return (
<button
onClick={() => {
selectedHobbyIndex.set(index);
}}
className="bg-indigo-600 text-white mb-2 w-full py-2 rounded-md"
>
{item.name.get()}
</button>
);
}}
</For>
<hr className="my-3" />
<div className="bg-gray-50 rounded-md p-2 grid grid-cols-2 gap-x-2">
{selectedHobby && (
<>
<Input item={selectedHobby.name} />
<Input item={selectedHobby.description} />
</>
)}
</div>
<hr className="my-3" />
<div className="bg-gray-50 rounded-md p-2 grid grid-cols-2">
<pre>{JSON.stringify(store, null, 2)}</pre>
</div>
</div>
);
}
function Input({ item }: { item: ObservablePrimitive<string> }) {
return <$React.input type="text" $value={item} className="border" />;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I am creating observables with classes like this
When I run this I get an error in the console
And when I log the selected hobby I get this

What am I doing wrong here?
Beta Was this translation helpful? Give feedback.
All reactions