Skip to content

Allow createContext get context to provide default value/work without parent context. #17062

@minht11

Description

@minht11

Describe the problem

In most cases context existing is the expected behavior and throwing error is good by default. Coming from other frameworks where you do it manually this saves time, however there are cases where context is optional.

Imagine pattern like useScrollContainer child component might be wrapped in <ScrollContainer />, but it might not be. Context not returning anything or defaulting to window intended. Useful with virtualization libraries.

To achieve this in Svelte you would need to use setContext/getContext, but they are not type safe. Given that createContext is new type-safe alternative, this use case should be supported as well, so there is only one way to do things.

Describe the proposed solution

Allow setting default value.

const [getContext, setContext] = createContext<number>()

const count = getContext(-1) // this will return -1 when no context is found.

Importance

nice to have

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions