Store
Store allows you to make data available everywhere throughout your app so that you don't have to fetch it everytime you want to access it.
Let's say you are developing a SaaS and users can join different workspace to work on different projects. You want to store the current 'workspace' so that everywhere in your app you know what workspace the user is working in.
Add a new object to the global store
- Open
/src/core/store/store.tsx
and edit theGlobalStoreContext
export type GlobalStoreContext = {
workspace: Workspace
setWorkspace: (workspace: Workspace) => void
}
- Edit the
GlobalStoreProvider
export const GlobalStoreProvider: React.FC<Props> = ({ children }) => {
const [workspace, setWorkspace] = useState<Organization>()
return (
<GlobalStoreContext.Provider
value={{
workspace,
setWorkspace,
}}
>
{children}
</GlobalStoreContext.Provider>
)
}
Use the store
- Set an object in the store
import { useGlobalStore } from '@/store'
const store = useGlobalStore()
const workspaceId = '123-123'
const workspace = await WorkspaceApi.findOne(workspaceId)
store.setWorkspace(workspace)
- Access an object in the store
import { useGlobalStore } from '@/store'
const store = useGlobalStore()
console.log(store.workspace)