Created
December 2, 2020 09:12
-
-
Save hising/7ca4ff9f950fee84de1d123afe8535a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useStaticRendering } from "mobx-react-lite"; | |
import { action, observable } from "mobx"; | |
import { useMemo } from "react"; | |
useStaticRendering(typeof window === "undefined"); | |
let companyStore; | |
interface CompanyServiceInterface { | |
loadCompany: (name: string) => {}; | |
} | |
class CompanyServiceClient implements CompanyServiceInterface{ | |
loadCompany(name: string): {} { | |
return {}; | |
} | |
} | |
class CompanyServiceBackend implements CompanyServiceInterface { | |
loadCompany(name: string): {} { | |
return {}; | |
} | |
} | |
class CompanyServiceFactory { | |
static create (isServer: boolean) { | |
return isServer ? new CompanyServiceBackend() : new CompanyServiceClient(); | |
} | |
} | |
export class CompanyStore { | |
@observable name = ""; | |
@observable orgNr = ""; | |
private companyService: CompanyServiceBackend | CompanyServiceClient; | |
hydrate(payload) { | |
if (!payload) { | |
return; | |
} | |
const isServer = typeof window === "undefined"; | |
this.companyService = CompanyServiceFactory.create(isServer); | |
} | |
@action | |
changeName(name: string) { | |
this.name = name; | |
} | |
async loadCompany(companyIdentifier: string) { | |
this.companyService.loadCompany(companyIdentifier); | |
} | |
} | |
const initializeStore = (initialData = null) => { | |
console.log(initialData); | |
const _store = companyStore ?? new CompanyStore(); | |
if (initialData) { | |
_store.hydrate(initialData); | |
} | |
if (typeof window === "undefined") return _store; | |
if (!companyStore) companyStore = _store; | |
return _store; | |
}; | |
export function useCompanyStore(initialState) { | |
return useMemo(() => initializeStore(initialState), [initialState]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment