Бабкины Семечки
Бабкины Семечки
SSolidJS
Created by Бабкины Семечки on 11/22/2024 in #support
Reactive conditional rendering based on Store of objects
Heres an example of what I am trying to do:
import { For, type Component } from "solid-js";
import { createStore } from "solid-js/store";

type Tag = {
id: number;
name: string;
};

const App: Component = () => {
const [allTags] = createStore<Array<Tag>>([
{ id: 0, name: "foo" },
{ id: 1, name: "bar" },
{ id: 2, name: "baz" },
]);

const [appliedTags, setAppliedTags] = createStore<Array<Tag>>([
{ id: 1, name: "bar" },
]);

return (
<>
<ul>
<For each={allTags}>
{(t) =>
appliedTags.some((v) => v.id === t.id) ? (
<li style={"font-weight: bold;"}>{t.name}</li>
) : (
<li>{t.name}</li>
)
}
</For>
</ul>
<button
onClick={() => {
setAppliedTags((cur) => [...cur, { id: 0, name: "foo" }]);
}}
>
Add "foo" tag
</button>
</>
);
};
import { For, type Component } from "solid-js";
import { createStore } from "solid-js/store";

type Tag = {
id: number;
name: string;
};

const App: Component = () => {
const [allTags] = createStore<Array<Tag>>([
{ id: 0, name: "foo" },
{ id: 1, name: "bar" },
{ id: 2, name: "baz" },
]);

const [appliedTags, setAppliedTags] = createStore<Array<Tag>>([
{ id: 1, name: "bar" },
]);

return (
<>
<ul>
<For each={allTags}>
{(t) =>
appliedTags.some((v) => v.id === t.id) ? (
<li style={"font-weight: bold;"}>{t.name}</li>
) : (
<li>{t.name}</li>
)
}
</For>
</ul>
<button
onClick={() => {
setAppliedTags((cur) => [...cur, { id: 0, name: "foo" }]);
}}
>
Add "foo" tag
</button>
</>
);
};
I have two Stores, containing Arrays of the same object. When displaying each object of one Store, I want to format the item based on whether or not the object can be found in the other Store. This is simple enough. However, when I update the second Store, I want the formatting on the displayed items to update reactively. So in this example, when you press the button to add the "foo" tag, the "foo" item printed above should become bold. Thank you for your assistance. (I know it would be easier, in this example, to just have a single Store and an "enabled" field on the Tag, however in my actual application, the above structure is necessary.)
46 replies