solid-primitives icon indicating copy to clipboard operation
solid-primitives copied to clipboard

Add `ConsumeContext`

Open FabianHummel opened this issue 10 months ago • 6 comments

Add a function to directly consume contexts within JSX. Inspired by React's Context.Consumer component, but nicely integrated with this primitive's createContextProvider.

Tests have been added and source code + README.md is documented

FabianHummel avatar Feb 15 '25 15:02 FabianHummel

🦋 Changeset detected

Latest commit: e71e4ad9eda2ea855d1b901c2d35c15d9d6b3cf4

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@solid-primitives/context Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

changeset-bot[bot] avatar Feb 15 '25 15:02 changeset-bot[bot]

this is a cool idea, but I don't like how you need a bound function (without parameters) to use it. When the default solid api for using the context is useContext(Ctx). At least it should be added to docs. To pass it as () => useContext(Ctx) or useContext.bind(null, Ctx) Also you can easily do this in solid and it will have the same effect

<Provider>
{untrack(() => {
    const value = useContext(Ctx)
    return <>{value}</>
})}
</Provider>

thetarnav avatar Feb 15 '25 16:02 thetarnav

If you mean the useFn parameter, yes, it would be better to change it to the context directly. Maybe allow for either of one, because I really like simply passing the use function that is returned from createContextProvider, especially because createContextProvider does not return the raw solidJS context:

<ConsumeContext context={counterContext}>
  {(ctx) => <>...</>}
</ConsumeContext>

// or

<ConsumeContext useFn={useCounter}>
  {(ctx) => <>...</>}
</ConsumeContext>

And for the easy alternative: <ConsumeContext> solely serves as syntactic sugar, just like <Show>, <For>, etc...

FabianHummel avatar Feb 15 '25 17:02 FabianHummel

Implemented the aforementioned ideas and added tests + docs

FabianHummel avatar Feb 16 '25 11:02 FabianHummel

what about

<ConsumeContext use={useMyContext}>
<ConsumeContext use={() => useContext(MyContext)}>
<ConsumeContext use={MyContext}>

by simply checking the typeof props.use?

Also it may be useful to mention in the docs that the prop will not be reactive.

thetarnav avatar Feb 16 '25 16:02 thetarnav

Oh, I totally forgot about this option, I will implement it later that day, thanks!

FabianHummel avatar Feb 17 '25 08:02 FabianHummel