Skip to content

Suggestion: Create a context with a required value #547

@scastiel

Description

@scastiel

Hi! In my company we use contexts widely, and for most of them we expect them to be mounted in the root store (if not, we want things to crash as soon as possible). This is how we define and use them:

const someContext = createContext<SomeType>()

// At initialization
someContext.setComputed(() => createSomeValue())

// In a store:
const value = someContext.get(this)
if (!value) throw new Error("Missing value")
// ...

This check helps us to guarantee that the context has a value, and makes TypeScript happy.

But it's quite verbose, and a use case we have in many places. So we created a tiny helper to create a context that must receive a value:

const createRequiredContext = <T>() => {
  const ctx = createContext<T>() as Context<T>
  ctx.setDefaultComputed(() => {
    throw new Error("Missing value for context")
  })
  return ctx
}

The code becomes a bit more concise as there is not need to check the returned value anymore:

const someContext = createRequiredContext<SomeType>()

// At initialization
someContext.setComputed(() => createSomeValue())

// In a store:
const value = someContext.get(this)
// No need to check, value is guaranteed to be defined :)

Just thought it could help other users. If such a helper could be in the lib (or even be part of the context API), it would be terrific 😉.

Thanks for all the work 👍

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions