I'm trying to initialize a Context with data loaded from a DB, but the setter function isn't working.
If the context is initialized from createServerData$ (look for [2] below), the getter returns the value from the store, but the setter is only ever called with undefined (look for [1]).
If the context is initialized from a constant [1, 2, 3], then both the getter and the setter work as expected.
My basic context provider looks like this:
export function NumsProvider(props: {init: number[], children?: JSXElement}) {
const [getter, setter] = createStore({nums: props.init})
const context = {
getter,
setter,
incr() {
setter("nums", all => {
console.log(`nums is ${JSON.stringify(all)}`) // [1] why is `all` undefined here?
return all?.map(one => one + 1)
})
},
}
return (
<NumsContext.Provider value={context}>
{props.children}
</NumsContext.Provider>
)
}
It's used in a basic parent component that wraps a child. The child uses the context.
export default function Parent() {
const nums = createServerData$(getNums) // getNums() gets Promise<number[]> from a DB
return (
<main>
<NumsProvider init={nums()}> // [2] if instead of nums() we just use [1, 2, 3], it works
<Child />
</NumsProvider>
</main>
)
}
The child just gets the values from the context and has a button to trigger the setter.
export default function Child() {
const { getter, incr } = useFakeStore()!
return (
<div>
<button type="submit" onClick={incr}>INCR</button>
<div>
<For each={getter.nums}>
{(item, index) => <div data-index={index()}>{JSON.stringify(item)}</div>}
</For>
</div>
</div>
)
}