From e90f8b688802372d2a337198405b402564c855e9 Mon Sep 17 00:00:00 2001 From: Fedor Katurov Date: Sun, 9 Jan 2022 19:32:37 +0700 Subject: [PATCH] fixed auth hydration --- src/store/auth/AuthStore.ts | 6 +++++- src/store/index.ts | 4 ++++ src/utils/context/StoreContextProvider.tsx | 7 +++++-- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/store/auth/AuthStore.ts b/src/store/auth/AuthStore.ts index bf872390..b3bd8b87 100644 --- a/src/store/auth/AuthStore.ts +++ b/src/store/auth/AuthStore.ts @@ -1,7 +1,7 @@ import { IUser } from '~/types/auth'; import { EMPTY_USER } from '~/constants/auth'; import { makeAutoObservable } from 'mobx'; -import { makePersistable } from 'mobx-persist-store'; +import { makePersistable, isHydrated } from 'mobx-persist-store'; export class AuthStore { token: string = ''; @@ -18,6 +18,10 @@ export class AuthStore { }); } + get isHydrated() { + return isHydrated(this); + } + get isUser() { return !!this.token; } diff --git a/src/store/index.ts b/src/store/index.ts index 24f06ac1..aac65654 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -13,6 +13,10 @@ export class Store { constructor() { makeAutoObservable(this); } + + get isHydrated() { + return this.auth.isHydrated; + } } const defaultStore = new Store(); diff --git a/src/utils/context/StoreContextProvider.tsx b/src/utils/context/StoreContextProvider.tsx index c3a858ee..3a0f91a3 100644 --- a/src/utils/context/StoreContextProvider.tsx +++ b/src/utils/context/StoreContextProvider.tsx @@ -1,10 +1,13 @@ import React, { createContext, FC, useContext } from 'react'; import { Store } from '~/store'; +import { observer } from 'mobx-react-lite'; export const StoreContext = createContext(new Store()); -export const StoreContextProvider: FC<{ store: Store }> = ({ children, store }) => { +export const StoreContextProvider: FC<{ store: Store }> = observer(({ children, store }) => { + if (!store.isHydrated) return null; + return {children}; -}; +}); export const useStore = () => useContext(StoreContext);