How to trigger update on resource update?
Do I need to pair each resource with signal to add item to the list that's originally loaded as resource?
7 Replies
We would need code to see what you did. Are you using
mutate
?Basically I load list of items from REST API:
const [list, setList] = createResource(async () => await (creates an array of objects here))
then I have a button to add new item. The handler makes POST of the item and then tried to add it to the list:
try {
await item.post()
list().push(item)
} catch (err) {
setErr(err)
}
And adding item to the list did not trigger update. Perhaps I need to call setList()
But then the above seems to be incorrect. I can only have
const [list] = createResource(async () => await (...))
thus, there is no setList() function.
SolidJS
Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.
ok, I switched to store, but I still don't get update:
const [list, setList] = createStore<EmailListItem[]>([])
const [listResource] = createResource(async () => await ... this loads array of objects)
createEffect(async () => {
if (!listResource.loading) {
setList(listResource)
}
})
// click event handler
const onAddToList: JSX.EventHandlerUnion<HTMLFormElement, Event & { submitter: HTMLElement}>|undefined = async (ev) => {
ev.preventDefault()
try {
await item.post()
listResource().push(item)
// setList(listResource)
} catch (err) {
setErr(err)
}
}
And then rendering code:
<For each={list}>{(listItem, idx) =>
<p class="item">{listItem.name}</p>
}
I think I figured it out. I basically had to follow https://www.solidjs.com/tutorial/stores_createstore?solved
Thank you. That little comment pointed me into the right direction.
SolidJS
Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.
hmm, in general having the separation between resource and store like that is not a good idea, because you have to manually synchronize them. Maybe a better approach will be to use the store as a backing signal for your resource, see
storage
option https://www.solidjs.com/docs/latest/api#createresource
this way, the resource fetches into the store directly, and then you can use the mutate
option to update the list as necessary. Note that there's a second return value from resource Thank you. I followed your advice.