1.0.1 • Published 3 years ago

use-guarded-context v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

use-guarded-context

useContext with fail-fast assertion. Tests if provider is mounted and throws an error if not

NPM JavaScript Style Guide

How it works?

Hook uses useContext under the hood. It enhances original one with assertion - checks if value is other than undefined .

What for?

See example:

Example

interface ProviderValue{
  someValue: unknown
}
// default value is undefined to fail fast
// rather than spend hours on debugging
const ExampleContext = React.createContext<ProviderValue | undefined>(undefined)

//...

const Component = () => {
  // regularValue: ProviderValue | undefined
  // you have to guard it by yourself
  const regularValue = useContext(ExampleContext)

  // safeValue: ProviderValue,
  // safe to use
  const safeValue = useGuardedContext(ExampleContext)

  //...
}

Installation

npm install use-guarded-context
//or
yarn add use-guarded-context

Usage

    import {useGuardedContext} from 'use-guarded-context'

    //in component
    const yourContextValue = useGuardedContext(YourContext)

If provider is not mounted anywhere above, error is thrown:

`Provider for context ${context.displayName} is not mounted`
1.0.1

3 years ago

1.0.0

3 years ago

0.2.0

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago