react-redux#useSelector TypeScript Examples

The following examples show how to use react-redux#useSelector. 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: Dashboard.tsx    From TutorBase with MIT License 6 votes vote down vote up
Dashboard = (params: IParams) => {
    let dispatch = useDispatch();
    let sidebarToggled = useSelector(selectSidebarToggled);
    let clientData = useSelector(selectClientData);
    const [loading, setLoading] = useState(true);
    const [isTutor, setIsTutor] = useState(false);
    useEffect(() => {
        const getTutor = async () => {
            return (await api.GetTutorById(clientData.clientId)).data[0];
        }
        getTutor().then(value => {
            setIsTutor(value !== null);
            dispatch(clientDataActions.setIsTutor((value !== null)));
            
        setLoading(false);
        }).catch(err => {
            
        setLoading(false);
        });
    });
    return (
        <div className={classNames("d-flex", (sidebarToggled) ? "toggled" : "")} id="dashboard-wrapper" style={{maxWidth:'100vw'}}>
            <Sidebar 
                mode={params.mode}
                isTutor = {isTutor}/>
            {params.mode === "Tutor" ? (isTutor ? <TutorPanel/> : <TutorPanelSignup isLoading={loading}/>) : <ClientPanel/>}
        </div>
    );
}
Example #2
Source File: IdeStatusbar.tsx    From kliveide with MIT License 6 votes vote down vote up
/**
 * Represents the status of the compiler
 * @returns
 */
function CompilerStatus() {
  const inProgress = useSelector(
    (state: AppState) => state?.compilation?.inProgress
  );
  const result = useSelector((state: AppState) => state?.compilation?.result);
  const filename = useSelector(
    (state: AppState) => state?.compilation?.filename
  );
  const errorCount = result?.errors?.length ?? 0;
  const icon = inProgress
    ? "settings-gear"
    : errorCount > 0
    ? "warning"
    : "check";
  return (
    <Section key="1">
      <Icon iconName="combine" style={{ marginRight: 8 }} />
      {filename && (
        <Icon iconName={icon} xclass={inProgress ? "rotating" : ""} />
      )}
      {filename && (
        <Label>
          ({getNodeFile(filename)}
          {errorCount > 0
            ? `, ${errorCount} ${errorCount === 1 ? "error" : "errors"}`
            : ""}
          )
        </Label>
      )}
    </Section>
  );
}
Example #3
Source File: hooks.ts    From cuiswap with GNU General Public License v3.0 6 votes vote down vote up
// returns all downloaded current lists
export function useAllLists(): TokenList[] {
  const lists = useSelector<AppState, AppState['lists']['byUrl']>(state => state.lists.byUrl)

  return useMemo(
    () =>
      Object.keys(lists)
        .map(url => lists[url].current)
        .filter((l): l is TokenList => Boolean(l)),
    [lists]
  )
}
Example #4
Source File: Step1.tsx    From frontend with GNU General Public License v3.0 6 votes vote down vote up
Step1 = (): JSX.Element => {
  const { register, errors } = useFormContext();

  const { onestep, twostep } = useSelector((state: RootState) => state.multiStepExample);

  return (
    <div>
      <Input
        label="test"
        placeholder="test"
        name="onestep"
        defaultValue={onestep}
        ref={register({ required: 'this is required' })}
        error={errors?.onestep?.message}
        fullWidth
      />
      <Input
        label="test"
        placeholder="test"
        name="twostep"
        defaultValue={twostep}
        ref={register({ required: 'this is required' })}
        error={errors?.twostep?.message}
        fullWidth
      />
    </div>
  );
}
Example #5
Source File: ProfilePage.tsx    From GiveNGo with MIT License 6 votes vote down vote up
StarColor = (props:any) => {
  const store = useSelector((state: any) => state.main)
  console.log('store att start color', store)
  let fill;
  if(!store.karma) fill = '#E4E9F2'
  if(store.karma > 0) fill = '#FFF3CD'
  if(store.karma > 4) fill = '#FFE49B'	
  if(store.karma > 7) fill = '#FFD169'	
  if(store.karma > 9) fill = '#FFBE43'	
  if(store.karma > 12) fill = '#FF9F05'
  if(store.karma > 15) fill = '#DB8003'
  return(
    <Icon {...props}
      width={32}
      height={32}
      fill={`${fill}`}
      name='star'/>
  )
}
Example #6
Source File: index.tsx    From GroupChat with MIT License 6 votes vote down vote up
BottomBar: React.FC<Props> = props => {
  const { username, image } = useSelector((state: IRootState) => state.auth);

  return (
    <div className={styles.container}>
      <div className={styles.wrapper}>
        <div className={styles.userBox}>
          <Tooltip title="Edit profile" placement="top">
            <img className={styles.image} alt="User" src={image} onClick={props.profileClick} />
          </Tooltip>

          <p className={styles.username}>{username}</p>
        </div>
        <div className={styles.buttonContainer}>
          <Tooltip title="Report a bug" placement="top">
            <IconButton className={styles.exitButton} onClick={props.bugClick}>
              <BugReportIcon className={styles.exit} />
            </IconButton>
          </Tooltip>
          <Tooltip title="Logout" placement="top">
            <IconButton className={styles.exitButton} onClick={props.exitClick}>
              <ExitToAppIcon className={styles.exit} />
            </IconButton>
          </Tooltip>
        </div>
      </div>
    </div>
  );
}
Example #7
Source File: member-collection.component.tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
MemberCollectionComponent = (props: Props) => {
  const memberCollection = useSelector((state: State) => state.memberReducer);
  const dispatch = useDispatch();
  
  // TODO Excercise port this to a table
  return (
    <>
      <button onClick={() => dispatch(memberRequest())}>Load</button>
      <ul>
        {memberCollection.map((member) => (
          <li>{member.login}</li>
        ))}
      </ul>
    </>
  );
}
Example #8
Source File: index.tsx    From lobis-frontend with MIT License 6 votes vote down vote up
// A component that displays error messages
function Messages() {
    const { enqueueSnackbar } = useSnackbar();
    const messages = useSelector<IReduxState, MessagesState>(state => state.messages);
    const dispatch = useDispatch();

    useEffect(() => {
        if (messages.message) {
            enqueueSnackbar(JSON.stringify(messages.message));
            dispatch(close());
        }
    }, [messages.message]);

    return <div></div>;
}
Example #9
Source File: Home.tsx    From hamagen-react-native with MIT License 6 votes vote down vote up
Home = () => {
  const { isRTL } = useSelector<Store, LocaleReducer>(state => state.locale);

  return (
    <>
      <Drawer.Navigator
        drawerType="back"
        screenOptions={{ gestureEnabled: false }}
        drawerContent={props => <DrawerContent {...props} />}
        drawerPosition={isRTL ? 'right' : 'left'}
        drawerStyle={{
          width: '100%'
        }}
      >
        <Drawer.Screen name="DrawerStack" component={DrawerStack} />
      </Drawer.Navigator>

      <MapModal />
    </>
  );
}
Example #10
Source File: index.tsx    From atorch-console with MIT License 6 votes vote down vote up
AtorchConsole: React.FC = () => {
  const dispatch = useDispatch();
  const connected = useSelector((state) => state.report.connected);
  const latest = useSelector((state) => state.report.latest);
  const onConnect = () => dispatch(connect());
  return (
    <Container className={locals.container}>
      <Row className='ml-2 justify-content-center'>
        <Button outline onClick={onConnect}>
          {connected ? 'Disconnect' : 'Connect'}
        </Button>
      </Row>
      <PrintReport packet={latest} />
    </Container>
  );
}
Example #11
Source File: History.tsx    From mops-vida-pm-watchdog with MIT License 6 votes vote down vote up
History = () => {
  const history = useSelector((state) => state.report.history);
  const onDownload = () => {
    const encoded = JSON.stringify(history, null, 2);
    const link = document.createElement('a');
    link.href = URL.createObjectURL(new Blob([encoded], { type: 'application/json' }));
    link.download = makeDownloadFile();
    link.click();
  };
  return (
    <Row hidden={history.length === 0}>
      <h1>
        History{' '}
        <Button size='sm' color='link' onClick={onDownload}>
          Download
        </Button>
      </h1>
      <Table responsive borderless size='sm'>
        <thead>
          <tr>
            <th>#</th>
            <th>
              PM <sub>2.5</sub>
            </th>
          </tr>
        </thead>
        <tbody>
          {history.map(({ recordDate, pm25 }, index) => (
            <tr key={index}>
              <td>{recordDate?.toLocaleString()}</td>
              <td>{pm25}</td>
            </tr>
          ))}
        </tbody>
      </Table>
    </Row>
  );
}
Example #12
Source File: LeftMenu.tsx    From Full-Stack-React-TypeScript-and-Node with MIT License 6 votes vote down vote up
LeftMenu = () => {
  const categoriesState = useSelector((state: AppState) => state.categories);
  const { width } = useWindowDimensions();
  const [categories, setCategories] = useState<JSX.Element>(
    <div>Left Menu</div>
  );

  useEffect(() => {
    if (categoriesState) {
      console.log(categoriesState);
      const cats = categoriesState.map((cat: Category) => {
        return (
          <li key={cat.id}>
            <Link to={`/categorythreads/${cat.id}`}>{cat.name}</Link>
          </li>
        );
      });
      setCategories(<ul className="category">{cats}</ul>);
    }
  }, [categoriesState]);

  if (width <= 768) {
    return null;
  }
  return <div className="leftmenu">{categories}</div>;
}
Example #13
Source File: LiveStreamFooter.tsx    From twitch-live-extension with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
LiveStreamFooter = () => {
    const classes = useStyles();
    const dispatch: AppDispatch = useDispatch();

    const { loading } = useSelector((state: RootState) => state.common);

    return (
        <div className={classes.root}>
            {!loading && (
                <Button
                    className={classes.button}
                    variant="outlined"
                    color="default"
                    size={'small'}
                    disabled={loading}
                    startIcon={<SyncIcon />}
                    onClick={() => dispatch(getLiveStreams())}
                >
                    Refresh
                </Button>
            )}

            <Button
                component={Link}
                className={classes.button}
                variant="outlined"
                size={'small'}
                disabled={loading}
                startIcon={<SettingsIcon />}
                to="/settings"
            >
                Settings
            </Button>
        </div>
    );
}
Example #14
Source File: useTransactionDeadline.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
// combines the block timestamp with the user setting to give the deadline that should be used for any submitted transaction
export default function useTransactionDeadline(): BigNumber | undefined {
  const ttl = useSelector<AppState, number>((state) => state.user.userDeadline);
  const blockTimestamp = useCurrentBlockTimestamp();
  return useMemo(() => {
    if (blockTimestamp && ttl) return blockTimestamp.add(ttl);
    return undefined;
  }, [blockTimestamp, ttl]);
}
Example #15
Source File: index.tsx    From rugenerous-frontend with MIT License 6 votes vote down vote up
// A component that displays error messages
function Messages() {
  const { enqueueSnackbar } = useSnackbar();
  const messages = useSelector<IReduxState, MessagesState>(state => state.messages);
  const dispatch = useDispatch();

  useEffect(() => {
    if (messages.message) {
      enqueueSnackbar(JSON.stringify(messages.message));
      dispatch(close());
    }
  }, [messages.message]);

  return <div></div>;
}
Example #16
Source File: index.tsx    From Fashionista with MIT License 6 votes vote down vote up
Header = () => {
  const [modal, setModal] = useState({ open: false, search: false });

  const { count } = useSelector((state: StoreState) => state.cart);

  return (
    <header className="header">
      <div className="header__container">
        <Logo height={40} width={120} />
        <Countries />
        <div className="header__icons">
          <Button onClick={() => setModal({ search: true, open: true })}>
            <SearchIcon />
          </Button>
          <Button onClick={() => setModal({ search: false, open: true })}>
            <ShoppingCartIcon />
            {count ? <span className="header__cart--qtde">{count}</span> : null}
          </Button>
        </div>
        <SearchModal
          isOpen={modal.search && modal.open}
          close={() => setModal({ ...modal, open: false })}
        />
        <BagModal
          isOpen={!modal.search && modal.open}
          close={() => setModal({ ...modal, open: false })}
        />
      </div>
    </header>
  );
}
Example #17
Source File: InGameWindow.tsx    From overwolf-modern-react-boilerplate with MIT License 5 votes vote down vote up
InGameWindow = () => {
  const { event, info } = useSelector((state: RootReducer) => state.background)

  useEffect(() => {
    console.info(
      '[? overwolf-modern-react-boilerplate][? InGameWindow][? useEffect - event]',
      JSON.stringify(event, null, 2),
    )
    // or use https://github.com/AlbericoD/overwolf-modern-react-boilerplate#-remote-redux-debug
  }, [event])

  useEffect(() => {
    console.info(
      '[? overwolf-modern-react-boilerplate][? InGameWindow][? useEffect -info]',
      JSON.stringify(info, null, 2),
    )
    // or use https://github.com/AlbericoD/overwolf-modern-react-boilerplate#-remote-redux-debug
  }, [info])

  return (
    <div className="in-game-container">
      <Title color="white">In Game Window</Title>
      <Feed
        title="Events"
        data={event.length ? event[0] : { content: 'No events yet' }}
      />
      <Feed
        title="Infos"
        data={Object.keys(info).length ? info : { content: 'No infos yet' }}
      />
    </div>
  )
}
Example #18
Source File: hooks.ts    From bluebubbles-server with Apache License 2.0 5 votes vote down vote up
useAppSelector: TypedUseSelectorHook<RootState> = useSelector
Example #19
Source File: MonitoringCard.tsx    From Pi-Tool with GNU General Public License v3.0 5 votes vote down vote up
MonitoringCard: React.FC = () => {
    const [open, setOpen] = React.useState(false);
    const metrics = useSelector((state: RootState) => state.monitoring.activeMetrics);

    const handleOpen = () => { setOpen(true); }
    const handleClose = () => { setOpen(false); }

    const cardActions = (
        <Box>
            <Tooltip title="Select metrics" placement="left">
                <IconButton aria-label="delete" color="default" onClick={handleOpen}>
                    <SettingsIcon />
                </IconButton>
            </Tooltip>
        </Box>
    );

    const activeMetrics = Object.keys(metrics)
        .filter(m => metrics[m as MonitoringMetric].active);

    const computeChartWidth = (len: number, idx: number) => {
        if (len > 1) {
            return (((idx % 2) === 0) && (idx === len - 1) ? '100%' : '50%');
        } else {
            return '100%';
        }
    }

    const charts = activeMetrics.map((metric, index) => (
        <Box width={computeChartWidth(activeMetrics.length, index)}>
            <MetricChart metric={metric as MonitoringMetric} key={`chart-${metric as string}`} />
        </Box>
    ));

    const noSelected = (charts.length === 0) && (
        <Box display="flex" justifyContent="center">
            <Typography>No metric selected.</Typography>
        </Box>
    );

    return (
        <MainCard title="Monitoring" actions={cardActions}>
            <MonitoringDialog open={open} onClose={handleClose} />
            <Box display="flex" flexWrap="wrap" width="100%" p={1}>
                {charts}
            </Box>

            {noSelected}
        </MainCard>
    );
}
Example #20
Source File: 1_subject.tsx    From TutorBase with MIT License 5 votes vote down vote up
/* Step one of the appointment scheduler is for
   the user to pick their tutor subject */
export function Step1() {
    let clientFlowData = useSelector(selectClientFlowData);
    let [subjects, setSubjects] = useState<Array<Subject>>([]);
    let dispatch = useDispatch();

    useEffect(() => {
        // Get all avaliable subjects from API
        const getSubjects = async () => {
            return (await api.GetSubjects()).data;
        }

        getSubjects().then(value => {
                setSubjects(value);
                dispatch(clientFlowActions.setAvailableSubjects(value));
            }
        )
    }, [])

    return (
        <Container>
            <h3 className="hr mt-1">Select a Subject</h3>
            <Cards>
                {subjects.length === 0 ? <div>No subjects found!</div> : <></>}
                {subjects.map((subject, index) => {
                    return <ClientFlowCard
                        onClick={() => {
                            dispatch(clientFlowActions.incrementStep());
                            dispatch(clientFlowActions.setSelectedSubject(subject));
                        }}
                        color={SubjectToColor(subject._id)}
                        title={subject.id}
                        checked={clientFlowData.selectedSubject.id === subject.id}
                    ></ClientFlowCard>
                })}
            </Cards>
        </Container>
    );
}
Example #21
Source File: KeyboardPanel.tsx    From kliveide with MIT License 5 votes vote down vote up
KeyboardPanel: React.VFC<Props> = ({ type }) => {
  // --- Component state
  const [width, setWidth] = useState(0);
  const [height, setHeight] = useState(0);

  // --- App state selectors
  const visible = useSelector((s: AppState) => s.emuViewOptions.showKeyboard);
  const layout = useSelector((s: AppState) => s.emulatorPanel.keyboardLayout);

  const hostElement = useRef<HTMLDivElement>();

  useEffect(() => {
    if (hostElement?.current) {
      setWidth(hostElement.current.offsetWidth);
      setHeight(hostElement.current.offsetHeight);
    }
  });

  // --- Handle resizing
  const _onResize = () => handleResize();

  useResizeObserver(hostElement, _onResize);

  let keyboard = null;
  switch (type) {
    case "sp48":
      keyboard = <Sp48Keyboard width={width} height={height} />;
      break;
    case "cz88":
      keyboard = <Cz88Keyboard width={width} height={height} layout={layout} />;
  }
  if (visible) {
    return (
      <div style={rootStyle} ref={hostElement}>
        {keyboard}
      </div>
    );
  }
  return null;

  async function handleResize(): Promise<void> {
    await animationTick();
    if (hostElement?.current) {
      setWidth(hostElement.current?.offsetWidth ?? 0);
      setHeight(hostElement.current?.offsetHeight ?? 0);
    }
  }
}
Example #22
Source File: useTypedSelector.ts    From GTAV-NativeDB with MIT License 5 votes vote down vote up
export default function useTypedSelector<TSelected>(selector: (state: RootState) => TSelected) {
  return useSelector(selector)
}
Example #23
Source File: hooks.ts    From keycaplendar with MIT License 5 votes vote down vote up
useAppSelector: TypedUseSelectorHook<RootState> = useSelector
Example #24
Source File: hooks.ts    From cuiswap with GNU General Public License v3.0 5 votes vote down vote up
export function useBlockNumber(): number | undefined {
  const { chainId } = useActiveWeb3React()

  return useSelector((state: AppState) => state.application.blockNumber[chainId ?? -1])
}
Example #25
Source File: AboutUsPage.tsx    From GiveNGo with MIT License 5 votes vote down vote up
AboutUsPage = () => {
  const dispatch = useDispatch()
  const store = useSelector((state: any) => state.main)
  
  return (
    <Layout
      style={{
        flex: 1,
        justifyContent: 'center',
        backgroundColor: 'white-ish',
      }}
    >
      <Card style={styles.card}>
        <Text category="p1" style={styles.text}>
          Give 'n' Go is here to connect people in need of basic goods with
          those who live nearby and are willing to donate and deliver those
          items.{'\n'}
          {'\n'}
          Our goal is to help build community while helping those in need. We
          hope that neighbors everywhere will use Give 'n' Go to support others
          in their neighborhood who are struggling to fulfill their basic needs
          due to illness, loss of job, change in childcare, or any other reason.
          This application is meant to make asking for what you need easy, and
          anyone nearby can help as little or as much as they are able to.
          {'\n'}
          {'\n'} Give what you can... and go!
        </Text>
      </Card>
    </Layout>
  );
}
Example #26
Source File: CartFinalPriceTable.tsx    From Shopping-Cart with MIT License 5 votes vote down vote up
CartFinalPriceTable: FC<PropTypes> = props => {
  const { dataSource, recommend } = props;
  const [discountPrice, setDiscountPrice] = useState<number>(0);
  const [defaultChecked, setDefaultChecked] = useState('unApplied');
  const couponData = useSelector(couponTypeSelector);
  const isNotRecommend: boolean = recommend.recommend === 'unApplied';

  // 자동 추천 기능
  useEffect(() => {
    setDefaultChecked(recommend.recommend);
    if (recommend.recommend === 'rate') {
      setDiscountPrice(dataSource.rateDiscountPrice);
    }
    if (recommend.recommend === 'amount') {
      setDiscountPrice(dataSource.amountDiscountPrice);
    }
    if (recommend.recommend === 'unApplied') {
      setDiscountPrice(0);
    }
  }, [dataSource, recommend]);

  const handleChange = useCallback(
    (event: RadioChangeEvent) => {
      setDefaultChecked(event.target.value);
      if (event.target.value === 'rate') {
        setDiscountPrice(dataSource.rateDiscountPrice);
      }
      if (event.target.value === 'amount') {
        setDiscountPrice(dataSource.amountDiscountPrice);
      }
      if (event.target.value === 'unApplied') {
        setDiscountPrice(0);
      }
    },
    [setDiscountPrice, dataSource],
  );

  return (
    <>
      {couponData ? (
        <Radio.Group
          value={defaultChecked}
          buttonStyle="solid"
          style={{ margin: '25px 50px 0 60px' }}
          onChange={handleChange}
        >
          <Radio value={'unApplied'} disabled={isNotRecommend}>
            쿠폰 미적용
          </Radio>
          <Radio value={couponData.rate.type} disabled={isNotRecommend}>
            {couponData.rate.title}
          </Radio>
          <Radio value={couponData.amount.type} disabled={isNotRecommend}>
            {couponData.amount.title}
          </Radio>
        </Radio.Group>
      ) : (
        ''
      )}
      <Descriptions bordered style={{ margin: '10px 50px 0 50px' }}>
        <Descriptions.Item label="총 상품 금액" span={2}>
          <PriceLabel value={dataSource.totalPrice} />
        </Descriptions.Item>
        <Descriptions.Item label="상품 할인 금액">
          <PriceLabel value={discountPrice} />
        </Descriptions.Item>
        <Descriptions.Item label="최종 가격" span={3}>
          <PriceLabel
            value={dataSource.totalPrice - discountPrice}
            large={true}
          />
        </Descriptions.Item>
      </Descriptions>
    </>
  );
}
Example #27
Source File: App.tsx    From GroupChat with MIT License 5 votes vote down vote up
App: React.FC = () => {
  const isAuth = useSelector((state: IRootState) => state.auth.isLogged);

  return isAuth ? <AppView /> : <AuthView />;
}
Example #28
Source File: index.tsx    From lobis-frontend with MIT License 5 votes vote down vote up
function ConnectMenu() {
    const { connect, disconnect, connected, web3, providerChainID, checkWrongNetwork } = useWeb3Context();
    const dispatch = useDispatch();
    const [isConnected, setConnected] = useState(connected);

    let pendingTransactions = useSelector<IReduxState, IPendingTxn[]>(state => {
        return state.pendingTransactions;
    });

    let buttonText = "Connect Wallet";
    let clickFunc: any = connect;
    let buttonStyle = {};

    if (isConnected) {
        buttonText = "Disconnect";
        clickFunc = disconnect;
    }

    if (pendingTransactions && pendingTransactions.length > 0) {
        buttonText = `${pendingTransactions.length} Pending `;
        clickFunc = () => {};
    }

    if (isConnected && providerChainID !== DEFAULD_NETWORK) {
        buttonText = "Wrong network";
        buttonStyle = { backgroundColor: "rgb(255, 67, 67)" };
        clickFunc = () => {
            checkWrongNetwork();
        };
    }

    useEffect(() => {
        setConnected(connected);
    }, [web3, connected]);

    return (
        <div className="connect-button" style={buttonStyle} onClick={clickFunc}>
            <p>{buttonText}</p>
            {pendingTransactions.length > 0 && (
                <div className="connect-button-progress">
                    <CircularProgress size={15} color="inherit" />
                </div>
            )}
        </div>
    );
}