SolidJSS
SolidJSโ€ข13mo agoโ€ข
16 replies
Eve

How to type the context from the docs example

Using the example from here I'm trying to get it working in TS, but TS doesn't seem to understand <CounterContext.Provider and throws all kinds of errors.

Does anyone know how to make this work?

import { createContext, createSignal, useContext } from "solid-js";
import type { ParentProps } from "solid-js";

const CounterContext = createContext<number>(0);

export function CounterProvider(props: ParentProps & { initialCount?: number }) {
  const [count, setCount] = createSignal(props.initialCount || 0);
  const counter = [
    count,
    {
      increment() {
        setCount(prev => prev + 1);
      },
      decrement() {
        setCount(prev => prev - 1);
      }
    }
  ];

  return (
    <CounterContext.Provider value={counter}>
      {props.children}
    </CounterContext.Provider>
  );
}

export function useCounter() { return useContext(CounterContext); }
Was this page helpful?