sveltejs / svelte

web development for the rest of us
https://svelte.dev
MIT License
79.93k stars 4.25k forks source link

Context not working with array #14261

Open dm-de opened 4 days ago

dm-de commented 4 days ago

Describe the bug

After setting an array, I use setContext inside $effect. This feels right - otherwise a warning come up. But my subcomponent do not get context. Array is undefined

Same thing with object

Reproduction

ARRAY

OBJECT

Logs

No response

System Info

Svelte 5.1.14

Severity

blocking an upgrade

paoloricciuti commented 4 days ago

setContext should be called inside the component script and not inside an effect (actually i'm surprised it's not erroring our might be worth taking a look).

The warning you get is because you are passing some stateful value and it's not within a closure so if the array itself updates the child will not get updates (you will still get updates in case a member of the array is updated).

You can either silence the warning if you know you will never reassign the array or wrap it in a getter/closure.

example with closure example with getter

dm-de commented 4 days ago

thx... I misunderstood that warning. I thought, I need to use $effect.

State referenced in its own scope will never update. Did you mean to reference it inside a closure?

so here is an summary: 1) missing error for setContext inside $effect 2) missing information in docs about passing function with setContext: https://svelte.dev/docs/svelte/svelte#setContext 3) missing this nice tricks in example https://svelte.dev/docs/svelte/context

paoloricciuti commented 4 days ago

missing information in docs about passing function with setContext: https://svelte.dev/docs/svelte/svelte#setContext

You don't HAVE to use functions with setContext you just need if you want to keep reactivity alive and that is true for every function boundary.

dm-de commented 4 days ago

According to the documentation, we should use an "arbitrary context object". Of course I also used Array. I just didn't expect it to work this with a function.