redux#bindActionCreators TypeScript Examples

The following examples show how to use redux#bindActionCreators. 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: Notification.tsx    From flame with MIT License 6 votes vote down vote up
Notification = (props: Props): JSX.Element => {
  const dispatch = useDispatch();
  const { clearNotification } = bindActionCreators(actionCreators, dispatch);

  const [isOpen, setIsOpen] = useState(true);
  const elementClasses = [
    classes.Notification,
    isOpen ? classes.NotificationOpen : classes.NotificationClose,
  ].join(' ');

  useEffect(() => {
    const closeNotification = setTimeout(() => {
      setIsOpen(false);
    }, 3500);

    const clearNotificationTimeout = setTimeout(() => {
      clearNotification(props.id);
    }, 3600);

    return () => {
      window.clearTimeout(closeNotification);
      window.clearTimeout(clearNotificationTimeout);
    };
  }, []);

  const clickHandler = () => {
    if (props.url) {
      window.open(props.url, '_blank');
    }
  };

  return (
    <div className={elementClasses} onClick={clickHandler}>
      <h4>{props.title}</h4>
      <p>{props.message}</p>
      <div className={classes.Pog}></div>
    </div>
  );
}
Example #2
Source File: ThemePreview.tsx    From flame with MIT License 6 votes vote down vote up
ThemePreview = ({
  theme: { colors, name },
}: Props): JSX.Element => {
  const { setTheme } = bindActionCreators(actionCreators, useDispatch());

  return (
    <div className={classes.ThemePreview} onClick={() => setTheme(colors)}>
      <div className={classes.ColorsPreview}>
        <div
          className={classes.ColorPreview}
          style={{ backgroundColor: colors.background }}
        ></div>
        <div
          className={classes.ColorPreview}
          style={{ backgroundColor: colors.primary }}
        ></div>
        <div
          className={classes.ColorPreview}
          style={{ backgroundColor: colors.accent }}
        ></div>
      </div>
      <p>{name}</p>
    </div>
  );
}
Example #3
Source File: index.tsx    From selftrace with MIT License 6 votes vote down vote up
mapDispatchToProps = (dispatch: Dispatch<Action>) =>
  bindActionCreators(
    {
      signinUser: SigninActions.signinUser,
      googleOAuthUser: SigninActions.googleOAuthUser,
      clearProgress: () => (d: Dispatch) => d(SigninActions.clearSigninProgress()),
    },
    dispatch
  )
Example #4
Source File: hooks.ts    From frontend-v1 with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useDeposits() {
  const { deposit, showConfirmationScreen } = useAppSelector(
    (state) => state.deposits
  );
  const dispatch = useAppDispatch();
  const actions = bindActionCreators({ depositAction, toggle }, dispatch);
  return {
    deposit,
    showConfirmationScreen,
    toggle: actions.toggle,
    addDeposit: actions.depositAction,
  };
}
Example #5
Source File: hooks.ts    From frontend-v1 with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useTransactions() {
  const { transactions } = useAppSelector((state) => state.transactions);
  const dispatch = useAppDispatch();
  const actions = bindActionCreators({ add }, dispatch);
  return {
    transactions,
    addTransaction: actions.add,
  };
}
Example #6
Source File: hooks.ts    From frontend-v1 with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useConnection() {
  const { account, signer, provider, error, chainId, notify, name } =
    useAppSelector((state) => state.connection);

  const dispatch = useAppDispatch();
  const actions = useMemo(
    () => bindActionCreators({ update, disconnect, errorAction }, dispatch),
    [dispatch]
  );

  const isConnected = !!chainId && !!signer && !!account;
  return {
    account,
    chainId,
    provider,
    signer,
    error,
    isConnected,
    setUpdate: actions.update,
    disconnect: actions.disconnect,
    setError: actions.errorAction,
    notify,
    name,
  };
}
Example #7
Source File: App.tsx    From flame with MIT License 5 votes vote down vote up
App = (): JSX.Element => {
  const { config, loading } = useSelector((state: State) => state.config);

  const dispath = useDispatch();
  const { fetchQueries, setTheme, logout, createNotification, fetchThemes } =
    bindActionCreators(actionCreators, dispath);

  useEffect(() => {
    // check if token is valid
    const tokenIsValid = setInterval(() => {
      if (localStorage.token) {
        const expiresIn = decodeToken(localStorage.token).exp * 1000;
        const now = new Date().getTime();

        if (now > expiresIn) {
          logout();
          createNotification({
            title: 'Info',
            message: 'Session expired. You have been logged out',
          });
        }
      }
    }, 1000);

    // load themes
    fetchThemes();

    // set user theme if present
    if (localStorage.theme) {
      setTheme(parsePABToTheme(localStorage.theme));
    }

    // check for updated
    checkVersion();

    // load custom search queries
    fetchQueries();

    return () => window.clearInterval(tokenIsValid);
  }, []);

  // If there is no user theme, set the default one
  useEffect(() => {
    if (!loading && !localStorage.theme) {
      setTheme(parsePABToTheme(config.defaultTheme), false);
    }
  }, [loading]);

  return (
    <>
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/settings" component={Settings} />
          <Route path="/applications" component={Apps} />
          <Route path="/bookmarks" component={Bookmarks} />
        </Switch>
      </BrowserRouter>
      <NotificationCenter />
    </>
  );
}
Example #8
Source File: index.tsx    From selftrace with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: Dispatch<Action>) =>
  bindActionCreators(
    {
      uploadUserInfo: Actions.uploadUserInfo,
      clearProgress: () => (d: Dispatch) => d(Actions.clearUpdateUserInfoProgress()),
    },
    dispatch
  )
Example #9
Source File: index.tsx    From selftrace with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: Dispatch<Action>) => bindActionCreators({}, dispatch)
Example #10
Source File: index.tsx    From selftrace with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: Dispatch<Action>) =>
  bindActionCreators(
    {
      resetUserPassword: Actions.resetUserPassword,
      clearProgress: () => (d: Dispatch) => d(Actions.clearResetPasswordProgress()),
    },
    dispatch
  )
Example #11
Source File: index.tsx    From selftrace with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: Dispatch<Action>) =>
  bindActionCreators(
    {
      signupUser: SignupActions.signupUser,
      clearProgress: () => (d: Dispatch) => d(SignupActions.clearSignupProgress()),
    },
    dispatch
  )
Example #12
Source File: ChangeLanguageButton.tsx    From hamagen-react-native with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: any) => {
  return bindActionCreators({
    toggleChangeLanguage
  }, dispatch);
}
Example #13
Source File: CategoryForm.tsx    From flame with MIT License 5 votes vote down vote up
CategoryForm = ({
  category,
  modalHandler,
}: Props): JSX.Element => {
  const dispatch = useDispatch();
  const { addCategory, updateCategory } = bindActionCreators(
    actionCreators,
    dispatch
  );

  const [formData, setFormData] = useState<NewCategory>(newCategoryTemplate);

  // Load category data if provided for editing
  useEffect(() => {
    if (category) {
      setFormData({ ...category });
    } else {
      setFormData(newCategoryTemplate);
    }
  }, [category]);

  const inputChangeHandler = (
    e: ChangeEvent<HTMLInputElement | HTMLSelectElement>,
    options?: { isNumber?: boolean; isBool?: boolean }
  ) => {
    inputHandler<NewCategory>({
      e,
      options,
      setStateHandler: setFormData,
      state: formData,
    });
  };

  // Category form handler
  const formSubmitHandler = (e: FormEvent): void => {
    e.preventDefault();

    if (!category) {
      addCategory(formData);
    } else {
      updateCategory(category.id, formData);
      modalHandler();
    }

    setFormData(newCategoryTemplate);
  };

  return (
    <ModalForm modalHandler={modalHandler} formHandler={formSubmitHandler}>
      <InputGroup>
        <label htmlFor="name">Category Name</label>
        <input
          type="text"
          name="name"
          id="name"
          placeholder="Social Media"
          required
          value={formData.name}
          onChange={(e) => inputChangeHandler(e)}
        />
      </InputGroup>

      <InputGroup>
        <label htmlFor="isPublic">Category visibility</label>
        <select
          id="isPublic"
          name="isPublic"
          value={formData.isPublic ? 1 : 0}
          onChange={(e) => inputChangeHandler(e, { isBool: true })}
        >
          <option value={1}>Visible (anyone can access it)</option>
          <option value={0}>Hidden (authentication required)</option>
        </select>
      </InputGroup>

      <Button>{category ? 'Update category' : 'Add new category'}</Button>
    </ModalForm>
  );
}
Example #14
Source File: StyleSettings.tsx    From flame with MIT License 5 votes vote down vote up
StyleSettings = (): JSX.Element => {
  const dispatch = useDispatch();
  const { createNotification } = bindActionCreators(actionCreators, dispatch);

  const [customStyles, setCustomStyles] = useState<string>('');

  useEffect(() => {
    axios
      .get<ApiResponse<string>>('/api/config/0/css')
      .then((data) => setCustomStyles(data.data.data))
      .catch((err) => console.log(err.response));
  }, []);

  const inputChangeHandler = (e: ChangeEvent<HTMLTextAreaElement>) => {
    e.preventDefault();
    setCustomStyles(e.target.value);
  };

  const formSubmitHandler = (e: FormEvent) => {
    e.preventDefault();

    axios
      .put<ApiResponse<{}>>(
        '/api/config/0/css',
        { styles: customStyles },
        { headers: applyAuth() }
      )
      .then(() => {
        createNotification({
          title: 'Success',
          message: 'CSS saved. Reload page to see changes',
        });
      })
      .catch((err) => console.log(err.response));
  };

  return (
    <form onSubmit={(e) => formSubmitHandler(e)}>
      <InputGroup>
        <label htmlFor="customStyles">Custom CSS</label>
        <textarea
          id="customStyles"
          name="customStyles"
          value={customStyles}
          onChange={(e) => inputChangeHandler(e)}
          spellCheck={false}
        ></textarea>
      </InputGroup>
      <Button>Save CSS</Button>
    </form>
  );
}
Example #15
Source File: ThemeBuilder.tsx    From flame with MIT License 5 votes vote down vote up
ThemeBuilder = ({ themes }: Props): JSX.Element => {
  const {
    auth: { isAuthenticated },
    theme: { themeInEdit, userThemes },
  } = useSelector((state: State) => state);

  const { editTheme } = bindActionCreators(actionCreators, useDispatch());

  const [showModal, toggleShowModal] = useState(false);
  const [isInEdit, toggleIsInEdit] = useState(false);

  useEffect(() => {
    if (themeInEdit) {
      toggleIsInEdit(false);
      toggleShowModal(true);
    }
  }, [themeInEdit]);

  useEffect(() => {
    if (isInEdit && !userThemes.length) {
      toggleIsInEdit(false);
      toggleShowModal(false);
    }
  }, [userThemes]);

  return (
    <div className={classes.ThemeBuilder}>
      {/* MODALS */}
      <Modal
        isOpen={showModal}
        setIsOpen={() => toggleShowModal(!showModal)}
        cb={() => editTheme(null)}
      >
        {isInEdit ? (
          <ThemeEditor modalHandler={() => toggleShowModal(!showModal)} />
        ) : (
          <ThemeCreator modalHandler={() => toggleShowModal(!showModal)} />
        )}
      </Modal>

      {/* USER THEMES */}
      <ThemeGrid themes={themes} />

      {/* BUTTONS */}
      {isAuthenticated && (
        <div className={classes.Buttons}>
          <Button
            click={() => {
              editTheme(null);
              toggleIsInEdit(false);
              toggleShowModal(!showModal);
            }}
          >
            Create new theme
          </Button>

          {themes.length ? (
            <Button
              click={() => {
                toggleIsInEdit(true);
                toggleShowModal(!showModal);
              }}
            >
              Edit user themes
            </Button>
          ) : (
            <></>
          )}
        </div>
      )}
    </div>
  );
}
Example #16
Source File: ThemeEditor.tsx    From flame with MIT License 5 votes vote down vote up
ThemeEditor = (props: Props): JSX.Element => {
  const {
    theme: { userThemes },
  } = useSelector((state: State) => state);

  const { deleteTheme, editTheme } = bindActionCreators(
    actionCreators,
    useDispatch()
  );

  const updateHandler = (theme: Theme) => {
    props.modalHandler();
    editTheme(theme);
  };

  const deleteHandler = (theme: Theme) => {
    if (window.confirm(`Are you sure you want to delete this theme?`)) {
      deleteTheme(theme.name);
    }
  };

  return (
    <ModalForm formHandler={() => {}} modalHandler={props.modalHandler}>
      <CompactTable headers={['Name', 'Actions']}>
        {userThemes.map((t, idx) => (
          <Fragment key={idx}>
            <span>{t.name}</span>
            <ActionIcons>
              <span onClick={() => updateHandler(t)}>
                <Icon icon="mdiPencil" />
              </span>
              <span onClick={() => deleteHandler(t)}>
                <Icon icon="mdiDelete" />
              </span>
            </ActionIcons>
          </Fragment>
        ))}
      </CompactTable>
    </ModalForm>
  );
}
Example #17
Source File: QuerySnippetNavigator.tsx    From querybook with Apache License 2.0 5 votes vote down vote up
function mapDispatchToProps(dispatch: Dispatch) {
    return {
        searchQuerySnippets: bindActionCreators(
            querySnippetsActions.searchQuerySnippets,
            dispatch
        ),
    };
}
Example #18
Source File: index.tsx    From selftrace with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: Dispatch<Action>) =>
  bindActionCreators(
    {
      uploadUserInfo: Actions.uploadUserInfo,
      clearProgress: () => (d: Dispatch) => d(Actions.clearUpdateUserInfoProgress()),
    },
    dispatch
  )
Example #19
Source File: ChangeLanguage.tsx    From hamagen-react-native with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: any) => {
  return bindActionCreators({
    changeLocale,
  }, dispatch);
}
Example #20
Source File: LocationHistory.tsx    From hamagen-react-native with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: any) => {
  return bindActionCreators({
    toggleWebview
  }, dispatch);
}
Example #21
Source File: Location.tsx    From hamagen-react-native with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: any) => {
  return bindActionCreators({
    toggleWebview
  }, dispatch);
}
Example #22
Source File: LocationHistoryOnBoarding.tsx    From hamagen-react-native with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: any) => {
  return bindActionCreators({
    toggleWebview
  }, dispatch);
}
Example #23
Source File: Welcome.tsx    From hamagen-react-native with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: any) => {
  return bindActionCreators({
    checkForceUpdate
  }, dispatch);
}
Example #24
Source File: index.tsx    From strapi-plugin-comments with MIT License 5 votes vote down vote up
export function mapDispatchToProps(dispatch) {
  return bindActionCreators({ setConfig }, dispatch);
}
Example #25
Source File: index.tsx    From strapi-plugin-comments with MIT License 5 votes vote down vote up
export function mapDispatchToProps(dispatch) {
  return bindActionCreators({}, dispatch);
}
Example #26
Source File: index.tsx    From selftrace with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: Dispatch<Action>) =>
  bindActionCreators(
    {
      updateUserPassword: Actions.updateUserPassword,
      clearProgress: () => (d: Dispatch) => d(Actions.clearUpdatePasswordProgress()),
    },
    dispatch
  )
Example #27
Source File: index.tsx    From selftrace with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: Dispatch<Action>) =>
  bindActionCreators(
    {
      signoutUser: SignoutActions.signoutUser,
      clearProgress: () => (d: Dispatch) => d(SignoutActions.clearSignoutProgress()),
    },
    dispatch
  )
Example #28
Source File: Layout.tsx    From selftrace with MIT License 5 votes vote down vote up
mapDispatchToProps = (dispatch: Dispatch<Action>) =>
  bindActionCreators(
    {
      subscribeToAuthStateChange: AuthStatusActions.subscribeToAuthStateChange,
    },
    dispatch
  )
Example #29
Source File: hooks.ts    From frontend-v1 with GNU Affero General Public License v3.0 5 votes vote down vote up
export function useSend() {
  const dispatch = useAppDispatch();
  const actions = bindActionCreators(
    {
      tokenAction,
      amountAction,
      fromChainAction,
      toChainAction,
      toAddressAction,
      sendErrorAction,
    },
    dispatch
  );
  const send = useAppSelector((state) => state.send);
  const sendAcross = useSendAcross();
  const sendOptimism = useSendOptimism();
  const sendArbitrum = useSendArbitrum();
  const sendBoba = useSendBoba();
  const setSend = {
    setToken: actions.tokenAction,
    setAmount: actions.amountAction,
    setFromChain: actions.fromChainAction,
    setToChain: actions.toChainAction,
    setToAddress: actions.toAddressAction,
    setError: actions.sendErrorAction,
  };

  if (send.fromChain === ChainId.MAINNET && send.toChain === ChainId.OPTIMISM) {
    return {
      ...send,
      ...setSend,
      ...sendOptimism,
    };
  }

  if (send.fromChain === ChainId.MAINNET && send.toChain === ChainId.ARBITRUM) {
    return {
      ...send,
      ...setSend,
      ...sendArbitrum,
    };
  }

  if (send.fromChain === ChainId.MAINNET && send.toChain === ChainId.BOBA) {
    return {
      ...send,
      ...setSend,
      ...sendBoba,
    };
  }

  return {
    ...send,
    ...setSend,
    ...sendAcross,
  };
}