1.0.12 • Published 5 years ago

@kollors/react-store v1.0.12

Weekly downloads
-
License
-
Repository
-
Last release
5 years ago

Установка

npm i @kollors/react-store

Использование

auth-store.ts

import { createStore } from '@kollors/react-store';

export interface CurrentUser {
  password: string;
  username: string;
}

export interface AuthState {
  currentUser: CurrentUser;
  isAuthenticated: boolean;
}

export const authStore = createStore({
  state: {} as AuthState,
  reducers: {
    setCurrentUser(state: AuthState, payload: CurrentUser) {
      return { ...state, currentUser: payload, isAuthenticated: !!payload };
    },
  },
});

root-store.ts

import { createRootStore } from '@kollors/react-store';
import { authStore } from './auth-store';

export const rootStore = createRootStore({
  authStore,
});

export type RootStore = ReturnType<typeof rootStore>;

app.tsx

import { useStore } from '@kollors/react-store';
import React, { ReactElement } from 'react';
import { RootStore } from './root-store';

export function App(): ReactElement {
  const { authStore } = useStore<RootStore>();

  const handleSignIn = () => {
    authStore.dispatch.setCurrentUser({ password: '1', username: '1' });
  };

  const handleSignOut = () => {
    authStore.dispatch.setCurrentUser(undefined);
  };

  return authStore.state.isAuthenticated ? (
    <div>
      Hello {authStore.state.currentUser.username}
      <button onClick={handleSignOut}>SignOut</button>
    </div>    
  ) : (
    <div>
      <button onClick={handleSignIn}>SignIn</button>
    </div>
  );
}

index.ts

import { StoreProvider } from '@kollors/react-store';
import { createElement } from 'react';
import { render } from 'react-dom';
import { rootStore } from './root-store';

document.addEventListener('DOMContentLoaded', () => {
  const rootApp = createElement(App);
  const storeProvider = createElement(StoreProvider, { rootStore }, rootApp);

  render(storeProvider, document.getElementById('root-app'));
});
1.0.12

5 years ago

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.3

5 years ago

1.0.0

5 years ago