assume all context values are nullable and create hooks to consume individual contexts #2449
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a little refactoring I wanted to throw in for how we consume the new contexts from
@graphiql/react
. The changes are:@graphiql/react
it is not clear which providers will actually be rendered by the user of the package. (Currently thegraphiql
package is the only user and it renderes all of them, but imho we can't assume that every future custom GraphQL IDE will do the same.)To make this more streamlined we create a custom
createNullableContext
function that wrapsReact.createContext
and passesnull
as default value. It also requires a generic type argument that we pass to the context.@graphiql/react
, i.e. we now douseEditorContext()
instead ofuseContext(EditorContext)
. We use a utility function to automatically generate these context hooks, which does some nice things for us:nonNull
. If this is set totrue
and the context value is empty, the hook throws an error. This makes is easy to consume a context value that is known to be non-null (because the necessary providers are all rendered higher up the tree). Typescript will also annotate the return type as non-null if setting this option.@graphiql/react
was actually using and we don't blame the internal use of the context hook, which would be not useful without knowing the implementation details of@graphiql/react
.