SolidJSS
SolidJSโ€ข2y agoโ€ข
17 replies
flippyflops

Reactivity in store

I think I may be missing the point of stores or just how to use them because I simply can't get it to trigger reactivity in a component. Below is a barebones example where I'm trying to have a value in a store and a function to update it - when the value changes I want to render it on the screen in a paragraph tag. Is there some obvious thing I'm missing here?

import { createContext, ParentProps, useContext } from "solid-js";
import { createStore } from "solid-js/store";

const FoobarContext = createContext<{
  name: string;
  changeName: () => void;
}>();

export const FoobarProvider = (props: ParentProps<unknown>) => {
  const [store, setStore] = createStore({
    name: "Jeff",
  });

  return (
    <FoobarContext.Provider
      value={{
        ...store,
        changeName: () => {
          setStore("name", "John");
        },
      }}
    >
      {props.children}
    </FoobarContext.Provider>
  );
};

const FoobarComponent = () => {
  const { name, changeName } = useContext(FoobarContext)!;

  return (
    <>
      <p>{name}</p>
      <button onClick={changeName}>Change Name</button>
    </>
  );
};

export const Foobar = () => (
  <FoobarProvider>
    <FoobarComponent />
  </FoobarProvider>
);
Was this page helpful?