open-feature / js-sdk

JavaScript SDK for OpenFeature
https://openfeature.dev
Apache License 2.0
145 stars 32 forks source link

[FEATURE] React SDK: Provide hook to set relevant context "`useContextMutator`" #968

Open toddbaert opened 3 months ago

toddbaert commented 3 months ago

Background

The OpenFeatureProvider React context provider binds an OpenFeature client to a React Context. Components within that boundary use the associated client for evaluations, etc. The client can be associated with a domain (see https://github.com/open-feature/js-sdk/blob/main/packages/react/README.md#multiple-providers-and-domains and https://github.com/open-feature/js-sdk/blob/main/packages/client/README.md#domains)

We do not currently have a hook that makes it easy to update this context. It's necessary to use the global object to do this. We should add a hook that allows the correct context for the enclosed scope to be set.

For example, this current implementation:

<OpenFeatureProvider domain={'my-domain'}>
  <button
    onClick={() => {
      OpenFeature.setContext('my-domain', updatedContext);
    }}
  >
      click here
  </button>
</OpenFeatureProvider>

Could be instead be:

<OpenFeatureProvider domain={'my-domain'}>
  <button
    onClick={() => {
      mutateContext(updatedContext); // function returned by new hook, associated with the 'my-domain' domain
    }}
  >
      click here
  </button>
</OpenFeatureProvider>

This would make things easier for users, and fit better into react idioms. Please test your solution but using it in the sample react app here.

Requirements

Additional Considerations

I'd love to see considerations from the implementor on the following:

wichopy commented 6 days ago

volunteer to tackle this one

wichopy commented 5 days ago

@toddbaert is there tooling to pull in the build with my changes in js sdk and use it with react test app project?

I was able to locally test manually using yalc but was wondering how you would go about it.

beeme1mr commented 4 days ago

Yalc is probably the easier way to try this in the test app.