SolidJSS
SolidJSโ€ข17mo agoโ€ข
2 replies
Wild

Create one global store with multiple createResource

Hello,
I am a beginner programmer developing a small local app with Tauri and SolidStart.
In the past, I have already worked on a personal website with Nuxt/Vue/Pinia.

The data being exclusively stored on a local sqlite database, I am trying to load all the data from the start of the program execution, and intend to make it available to all components from a store.

How do I initialize my store within context with createResource ? my context is undefined

I've made sure the data fetching part works. I tried to wrap the AppContext.Provider with Suspense, my guess being the async is messing things up here. Thank you

export type AppContextType = {
  store: Store<any>;
  setStore: SetStoreFunction<any>;
};

const AppContext = createContext<AppContextType>();

async function fetchDbData<T>(query: string) {
  const db = await Database.load("sqlite:mydatabase.db");
  return await db.select<T[]>(query);
}

const categories = createResource(async () =>
  fetchDbData<Category>("SELECT * FROM category;"),
)[0]();

const items = createResource(async () =>
  fetchDbData<Item>("SELECT * FROM item;"),
)[0]();

export const AppProvider: Component<any> = (props: any) => {
  // function createDeepSignal<T>(value: T): Signal<T> {
  //   const [store, setStore] = createStore({
  //     value,
  //   });
  //   return [
  //     () => store.value,
  //     (v: T) => {
  //       const unwrapped = unwrap(store.value);
  //       typeof v === "function" && (v = v(unwrapped));
  //       setStore("value", reconcile(v));
  //       return store.value;
  //     },
  //   ] as Signal<T>;
  // }

  const [store, setStore] = createStore(
    {
      categories,
      items
    });
  return (
    <AppContext.Provider value={{ store, setStore }}>
      {props.children}
    </AppContext.Provider>
  );
};

export const useStore = () => {
  const context = useContext(AppContext);
  if (!context) throw new Error("AppContext is not valid");
  return context;
};
Was this page helpful?