Zustand Store Creation before React

Hey, I was wondering how you could initialise a zustand store outside of react context entirely. Say i have
import DataRepository from "businesslogic/DataRepository";
import DbContext from "models/DbContext";
import { create } from "zustand";

type UseDBContext = {
dbContext: DbContext | null;
initialized: boolean;
init: () => Promise<void>;
};
export const useDBContext = create<UseDBContext>((set, get) => ({
dbContext: null,
initialized: false,
init: async () => {
let context = await DataRepository.initialize();
set({ dbContext: context, initialized: true });
},
}));
import DataRepository from "businesslogic/DataRepository";
import DbContext from "models/DbContext";
import { create } from "zustand";

type UseDBContext = {
dbContext: DbContext | null;
initialized: boolean;
init: () => Promise<void>;
};
export const useDBContext = create<UseDBContext>((set, get) => ({
dbContext: null,
initialized: false,
init: async () => {
let context = await DataRepository.initialize();
set({ dbContext: context, initialized: true });
},
}));
Now the only way i can initiate a DbContext is via the DataRepository.initialize() method. However, i dont want my dbContext to have to be null or undefined before it's initialised. I want dbContext to always have a value, and i dont really need/want the store to have to store the other params. Now an easy solution outside of the react work is DI, inject the service where you need it. In this case its not really possible in react. I can create a factory to do like
function createDBContextStore(dbContext: DB Context) {
return create((set) => ({
dbContext,
}));
}
function createDBContextStore(dbContext: DB Context) {
return create((set) => ({
dbContext,
}));
}
However this then means i dont have the global hook anymore... Any suggestions would be great.
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server