@/store#Store TypeScript Examples

The following examples show how to use @/store#Store. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GameWithReactRedux.test.tsx    From minesweeper with MIT License 6 votes vote down vote up
it('GameWithReactRedux renders correctly', () => {
  const { asFragment } = render(
    <Provider store={store}>
      <GameWithReactRedux />
    </Provider>
  );

  expect(asFragment()).toMatchSnapshot();
});
Example #2
Source File: Grid.test.tsx    From minesweeper with MIT License 6 votes vote down vote up
describe('Grid test cases', () => {
  it('Check Grid callbacks', () => {
    const { asFragment } = render(
      <Provider store={store}>
        <Grid />
      </Provider>
    );
    expect(asFragment()).toMatchSnapshot();

    userEvent.click(screen.getByTestId('0,0'));
    expect(asFragment()).toMatchSnapshot();

    userEvent.click(screen.getByTestId('8,8'), { button: 2 });
    expect(asFragment()).toMatchSnapshot();
  });
});
Example #3
Source File: Scoreboard.test.tsx    From minesweeper with MIT License 6 votes vote down vote up
describe('Scoreboard test cases', () => {
  it('Scoreboard check', () => {
    const mockDispatch = jest.fn();
    (useDispatch as jest.Mock).mockReturnValue(mockDispatch);
    (useSelector as jest.Mock).mockReturnValue({
      level: 'beginner',
      time: 0,
      bombs: 10,
      flagCounter: 3,
    });

    const { asFragment } = render(
      <Provider store={store}>
        <Scoreboard />
      </Provider>
    );

    expect(asFragment()).toMatchSnapshot();

    userEvent.selectOptions(screen.getByRole('combobox'), 'intermediate');
    expect(mockSetSearchParams).toHaveBeenCalledWith({ level: 'intermediate' });
    expect(asFragment()).toMatchSnapshot();

    userEvent.click(screen.getByRole('button'));
    expect(mockDispatch).toHaveBeenCalledTimes(2);
  });
});
Example #4
Source File: MinesweeperWithReactRedux.test.tsx    From minesweeper with MIT License 6 votes vote down vote up
it('MinesweeperWithReactRedux renders correctly', () => {
  const { asFragment } = render(
    <Provider store={store}>
      <MinesweeperWithReactRedux />
    </Provider>
  );

  expect(asFragment()).toMatchSnapshot();
});
Example #5
Source File: http.ts    From nebula-dashboard with Apache License 2.0 6 votes vote down vote up
service.interceptors.response.use(
  (response: any) => {
    const { code, message } = response.data;
    let _code;
    if ('code' in response.data) {
      _code = code;
    } else {
      // response from prometheus api
      _code = response.data.status === 'success' ? 0 : -1;
      response.data.code = _code;
    }
    // if connection refused, login again
    if (
      code === -1 &&
      message &&
      (message.includes('connection refused') ||
        message.includes('an existing connection was forcibly closed'))
    ) {
      AntdMessage.warning(intl.get('configServer.connectError'));
      store.dispatch({
        type: 'app/asyncLogout',
      });
    } else if (code === -1 && message) {
      AntdMessage.warning(message);
    }
    return response.data;
  },
  (error: any) => {
    AntdMessage.error(
      `${intl.get('common.requestError')}: ${error.response.status} ${
        error.response.statusText
      }`,
    );
    return error.response;
  },
);
Example #6
Source File: DynmapTileLayer.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
private readonly _store: Store = useStore();
Example #7
Source File: main.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
console.info(`LiveAtlas version ${store.state.version} - https://github.com/JLyne/LiveAtlas`);
Example #8
Source File: main.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
store.subscribe((mutation, state) => {
	if(mutation.type === 'toggleSidebarSectionCollapsedState' || mutation.type === 'setSidebarSectionCollapsedState') {
		localStorage.setItem('uiSettings', JSON.stringify({
			sidebar: state.ui.sidebar,
		}));
	}
});
Example #9
Source File: store.ts    From passwords-fountain with MIT License 5 votes vote down vote up
mergeState = <T>(moduleName: keyof AppState) => (
    changedState: Partial<T>
): Partial<AppState> => ({
    [moduleName]: { ...store.getState()[moduleName], ...changedState },
})
Example #10
Source File: store.ts    From passwords-fountain with MIT License 5 votes vote down vote up
callAction = (
    action: Action<AppState>,
    ...args: any[]
): Promise<void> | void => {
    return store.action(action)(...args);
}
Example #11
Source File: App.tsx    From minesweeper with MIT License 5 votes vote down vote up
App: FC = () => (
  <Provider store={store}>
    <BrowserRouter>
      <Navigation />
      <Routing />
    </BrowserRouter>
  </Provider>
)
Example #12
Source File: GameOver.test.tsx    From minesweeper with MIT License 5 votes vote down vote up
describe('GameOver test cases', () => {
  it('GameOver with loose check', () => {
    const mockDispatch = jest.fn();

    (useDispatch as jest.Mock).mockReturnValue(mockDispatch);
    (useSelector as jest.Mock).mockReturnValue({
      isGameOver: true,
      isWin: false,
    });

    const { asFragment } = render(
      <Provider store={store}>
        <GameOver />
      </Provider>
    );

    expect(asFragment()).toMatchSnapshot();

    userEvent.click(screen.getByText('?'));

    expect(mockDispatch).toHaveBeenCalled();
  });
  it('GameOver with win check', () => {
    const mockDispatch = jest.fn();

    (useDispatch as jest.Mock).mockReturnValue(mockDispatch);
    (useSelector as jest.Mock).mockReturnValue({
      isGameOver: true,
      isWin: true,
    });

    const { asFragment } = render(
      <Provider store={store}>
        <GameOver />
      </Provider>
    );

    expect(asFragment()).toMatchSnapshot();

    userEvent.click(screen.getByText('?'));

    expect(mockDispatch).toHaveBeenCalled();
  });
});
Example #13
Source File: withRedux.tsx    From react-js-tutorial with MIT License 5 votes vote down vote up
// if you want to get more info
// try to check https://gist.github.com/gaearon/1d19088790e70ac32ea636c025ba424e
export function withRedux(
  TargetComponent: React.ComponentType<Props>,
  getPropsFromRedux: (state: State) => Partial<Props>
): React.ComponentType<Props> {
  class WrappedComponent extends React.Component<
    Omit<Props, keyof ReturnType<typeof getPropsFromRedux>>,
    State
  > {
    storeSubscription?: () => void;

    state: ReturnType<typeof getPropsFromRedux> = getPropsFromRedux(
      store.getState()
    );

    render() {
      return (
        <TargetComponent
          dispatch={store.dispatch}
          {...this.state}
          {...this.props}
        />
      );
    }

    componentDidMount() {
      this.storeSubscription = store.subscribe(() =>
        this.setState(getPropsFromRedux(store.getState()))
      );
    }

    componentWillUnmount() {
      this.storeSubscription && this.storeSubscription();
    }
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  (WrappedComponent as any).displayName = `${TargetComponent.displayName}ConnectedToRedux`;

  return WrappedComponent;
}
Example #14
Source File: overlay.actions.spec.ts    From passwords-fountain with MIT License 4 votes vote down vote up
describe('Overlay actions', () => {
    afterEach(() => {
        jest.restoreAllMocks();
    });

    describe('hideSnackbar', () => {
        it('removes snackbar message from snackbarMessages list', () => {
            const state = {
                overlay: {
                    snackbarMessages: [
                        { id: 0, messageKey: 'Hello', type: 'success' },
                        { id: 1, messageKey: 'Bye', type: 'error' },
                    ],
                },
            };
            jest.spyOn(store, 'getState').mockReturnValue(state as any);
            const newState = overlayActions.hideSnackbar(state as AppState, 0);

            expect(newState).toEqual({
                overlay: {
                    snackbarMessages: [
                        { id: 1, messageKey: 'Bye', type: 'error' },
                    ],
                },
            });
        });
    });

    describe('showSnackbar', () => {
        it('adds snackbar message to the end of snackbarMessages list ', () => {
            const state = {
                overlay: {
                    snackbarMessages: [
                        { id: 0, messageKey: 'Hello', type: 'success' },
                        { id: 1, messageKey: 'Bye', type: 'error' },
                    ],
                },
            };
            jest.spyOn(store, 'getState').mockReturnValue(state as any);

            const newState = overlayActions.showSnackbar(
                state as AppState,
                'Nice to meet you',
                'info'
            );

            expect(newState).toEqual({
                overlay: {
                    snackbarMessages: [
                        { id: 0, messageKey: 'Hello', type: 'success' },
                        { id: 1, messageKey: 'Bye', type: 'error' },
                        {
                            id: expect.any(Number),
                            messageKey: 'Nice to meet you',
                            type: 'info',
                        },
                    ],
                },
            });
        });
    });

    describe('showGlobalLoader', () => {
        it('changes isGlobalLoaderVisible to TRUE', () => {
            jest.spyOn(store, 'getState').mockReturnValue({
                overlay: {
                    isGlobalLoaderVisible: false,
                },
            } as any);
            const newState = overlayActions.showGlobalLoader();

            expect(newState).toEqual({
                overlay: { isGlobalLoaderVisible: true },
            });
        });
    });

    describe('hideGlobalLoader', () => {
        it('changes isGlobalLoaderVisible to FALSE', () => {
            jest.spyOn(store, 'getState').mockReturnValue({
                overlay: {
                    isGlobalLoaderVisible: true,
                },
            } as any);
            const newState = overlayActions.hideGlobalLoader();

            expect(newState).toEqual({
                overlay: { isGlobalLoaderVisible: false },
            });
        });
    });
});
Example #15
Source File: passwordList.actions.ts    From passwords-fountain with MIT License 4 votes vote down vote up
passwordListActions = {
    switchOptionPanelVariant: (
        appState: AppState,
        optionPanelVariantName: OptionsPanelVariantName
    ): Partial<AppState> => {
        return merge({
            currentOptionPanelVariantName: optionPanelVariantName,
        });
    },
    resetSelectedAndDecryptedEntity: (): Partial<AppState> => {
        return merge({
            selectedAndDecryptedEntity: {} as PasswordEntityPayloadReferable,
        });
    },
    setSelectedAndDecryptedEntity: (
        appState: AppState,
        entity: PasswordEntityPayloadReferable
    ): Partial<AppState> => {
        return merge({
            selectedAndDecryptedEntity: entity,
        });
    },
    fetchPasswords: async (
        appState: AppState,
        masterKey: string,
        adminKey: string,
        forceReconnect = false
    ): Promise<Partial<AppState>> => {
        callAction(overlayActions.showGlobalLoader);
        const { fetchAllPasswordEntities } = await import(
            '@/modules/database/database.service'
        );

        if (!selectIsClientSet(appState) || forceReconnect) {
            await callAction(databaseActions.setClient, masterKey, adminKey);
        }

        const client = selectClient(store.getState()) as Client;

        try {
            const passwords = await fetchAllPasswordEntities(client);
            callAction(overlayActions.hideGlobalLoader);
            callAction(
                overlayActions.showSnackbar,
                'snackbar.passwordsFetchedSuccessfully',
                'success'
            );
            callAction(
                passwordListActions.switchOptionPanelVariant,
                optionsPanelVariantNames.entityFormCollapsed
            );

            return merge({ passwords });
        } catch (err) {
            callAction(overlayActions.hideGlobalLoader);
            callAction(
                overlayActions.showSnackbar,
                'snackbar.couldNotFetchPasswords',
                'error'
            );
            return merge({});
        }
    },
    addNewPassword: async (
        appState: AppState,
        newEntityPayload: PasswordEntityPayload,
        masterKey: string
    ): Promise<Partial<AppState>> => {
        callAction(overlayActions.showGlobalLoader);
        const { createPasswordEntity } = await import(
            '@/modules/database/database.service'
        );
        const { encrypt } = await import('@/modules/cipher/cipher.service');

        const client = selectClient(store.getState()) as Client;

        try {
            const encryptedPasswordEntity = encrypt(
                {
                    login: newEntityPayload.login,
                    password: newEntityPayload.password,
                },
                masterKey,
                true
            );
            await createPasswordEntity(client, {
                label: newEntityPayload.label,
                value: encryptedPasswordEntity,
            });
            callAction(overlayActions.hideGlobalLoader);
            callAction(
                passwordListActions.switchOptionPanelVariant,
                optionsPanelVariantNames.entityFormCollapsed
            );
        } catch (err) {
            callAction(overlayActions.hideGlobalLoader);
            callAction(
                overlayActions.showSnackbar,
                'snackbar.couldNotCreateNewPassword',
                'error'
            );
        } finally {
            return merge({});
        }
    },
    editPassword: async (
        appState: AppState,
        entityPayload: PasswordEntityPayloadReferable,
        masterKey: string
    ): Promise<Partial<AppState>> => {
        callAction(overlayActions.showGlobalLoader);
        const { updatePasswordEntity } = await import(
            '@/modules/database/database.service'
        );
        const { encrypt } = await import('@/modules/cipher/cipher.service');

        const client = selectClient(store.getState()) as Client;

        try {
            const encryptedPasswordEntity = encrypt(
                {
                    login: entityPayload.login,
                    password: entityPayload.password,
                },
                masterKey,
                true
            );
            await updatePasswordEntity(client, entityPayload.refId, {
                label: entityPayload.label,
                value: encryptedPasswordEntity,
            });
            callAction(overlayActions.hideGlobalLoader);
            callAction(passwordListActions.resetSelectedAndDecryptedEntity);
            callAction(
                passwordListActions.switchOptionPanelVariant,
                optionsPanelVariantNames.entityFormCollapsed
            );
        } catch (err) {
            callAction(overlayActions.hideGlobalLoader);
            callAction(
                overlayActions.showSnackbar,
                'snackbar.couldNotEditPassword',
                'error'
            );
        } finally {
            return merge({});
        }
    },
    removePassword: async (
        appState: AppState,
        refId: string
    ): Promise<Partial<AppState>> => {
        callAction(overlayActions.showGlobalLoader);
        const { deletePasswordEntity } = await import(
            '@/modules/database/database.service'
        );

        const client = selectClient(store.getState()) as Client;

        try {
            await deletePasswordEntity(client, refId);
            callAction(overlayActions.hideGlobalLoader);
        } catch (err) {
            callAction(overlayActions.hideGlobalLoader);
            callAction(
                overlayActions.showSnackbar,
                'snackbar.couldNotRemovePassword',
                'error'
            );
        } finally {
            return merge({});
        }
    },
}