project: organize mobx files

This commit is contained in:
Chika 2022-04-28 18:34:42 +03:00
parent 05980e1099
commit e6433f122c
5 changed files with 34 additions and 31 deletions

View File

@ -1,5 +1,5 @@
import { observer } from 'mobx-react-lite';
import { useStore } from 'stores/Provider';
import { useStore } from 'stores/hooks';
import styled from 'styled-components';
import { Flex } from 'UIKit/grid';
import { min } from 'UIKit/mq';

View File

@ -4,10 +4,10 @@ import { useApollo } from 'apollo/hooks';
import Layout from 'Components/Layout';
import type { AppProps } from 'next/app';
import Head from 'next/head';
import { StoreProvider } from 'stores/Provider';
import { ThemeProvider } from 'styled-components';
import { GlobalStyle } from 'UIKit/colors';
import theme from 'UIKit/theme';
import { StoreProvider } from '../stores/Provider';
import '../styles/globals.css';
if (process.env.NODE_ENV === 'development') {

View File

@ -1,32 +1,4 @@
import { createContext, useContext } from 'react';
import { RootStore } from './root';
/** @type{RootStore} */
let store;
const StoreContext = createContext(store);
export function useStore() {
const context = useContext(StoreContext);
if (context === undefined) {
throw new Error('useStore must be used within StoreProvider');
}
return context;
}
function initializeStore(initialData) {
const _store = store ?? new RootStore();
if (initialData) {
const { user } = initialData;
_store.$user.hydrate(user);
}
if (typeof window === 'undefined') return _store;
if (!store) store = _store;
return _store;
}
import { initializeStore, StoreContext } from '.';
export function StoreProvider({ children, ...initialData }) {
const store = initializeStore(initialData);

11
stores/hooks.js Normal file
View File

@ -0,0 +1,11 @@
import { useContext } from 'react';
import { StoreContext } from '.';
export function useStore() {
const context = useContext(StoreContext);
if (context === undefined) {
throw new Error('useStore must be used within StoreProvider');
}
return context;
}

20
stores/index.js Normal file
View File

@ -0,0 +1,20 @@
import { createContext } from 'react';
import { RootStore } from './root';
/** @type{RootStore} */
let store;
export const StoreContext = createContext(store);
export function initializeStore(initialData) {
const _store = store ?? new RootStore();
if (initialData) {
const { user } = initialData;
_store.$user.hydrate(user);
}
if (typeof window === 'undefined') return _store;
if (!store) store = _store;
return _store;
}