react-router#Redirect TypeScript Examples

The following examples show how to use react-router#Redirect. 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: App.tsx    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
function AppComponent(props: { history: History }): React.ReactElement {
  return (
    <ConnectedRouter history={props.history}>
      <Head />
      <Layout history={props.history}>
        <AppAlertGroup />
        <Suspense fallback={Fallback}>
          <Switch>
            <Routes />
            <Redirect path='*' to='/' />
          </Switch>
        </Suspense>
      </Layout>
    </ConnectedRouter>
  );
}
Example #2
Source File: TourLauncher.tsx    From ra-enterprise-demo with MIT License 6 votes vote down vote up
TourLauncher: FC = () => {
    const { tour } = useParams<{ tour: string }>();
    const [{ running }, { start }] = useTour();

    useEffect(() => {
        if (start && !running) {
            start(tour);
            return;
        }
    });

    return running ? <Redirect to="/" /> : null;
}
Example #3
Source File: AccountPage.tsx    From disco-cube-admin with MIT License 6 votes vote down vote up
AccountPage: React.FC<Props> = ({}) => {
  const { user } = useStore(authStore);
  if (!user) return <Redirect to={routes.login.path()} />;
  return (
    <Page>
      <AccountPageContent userEmail={user.email + ""} onLogout={() => logoutEffect()} />
    </Page>
  );
}
Example #4
Source File: LoginPage.tsx    From disco-cube-admin with MIT License 6 votes vote down vote up
LoginPage: React.FC<Props> = ({}) => {
  const { isLoggingIn, user } = useStore(authStore);

  if (user) return <Redirect to={routes.stats.path()} />;

  return (
    <Vertical horizontalAlign="center" verticalAlign="center">
      <LoginContent loading={isLoggingIn} onLogin={loginEffect} />
    </Vertical>
  );
}
Example #5
Source File: StatsPage.tsx    From disco-cube-admin with MIT License 6 votes vote down vote up
StatsPage: React.FC<Props> = ({}) => {
  const { user } = useStore(authStore);
  const cube = useStore(cubeStore);
  const fullSystemInfo = useStore(fullSystemInfoStore);
  const essential = useStore(essentialStatsStore);

  if (!user) return <Redirect to={routes.login.path()} />;

  return (
    <Page>
      <StatsPageContent
        isConnected={cube.status === "online"}
        statusChangedAt={cube.statusChangedAt}
        cpuLoadsPercent={essential.cpuLoadsPercent}
        memUsagePercent={essential.memUsagePercent}
        allSystemInfo={fullSystemInfo}
        cpuTemperature={essential.cpuTemperature}
      />
    </Page>
  );
}
Example #6
Source File: WhiteboardCreatorPage.tsx    From whiteboard-demo with MIT License 6 votes vote down vote up
public render(): React.ReactNode {
        const {uuid, userId, foundError} = this.state;
        const {identity,region} = this.props.match.params;
        const query = new URLSearchParams(window.location.search);
        const h5Url = query.get("h5Url");
        let url = `/whiteboard/${identity}/${uuid}/${userId}/${region}`;
        if (h5Url) {
            url = url + `?h5Url=${encodeURIComponent(h5Url)}`;
        }
        if (foundError) {
            return <PageError/>;
        } else if (localStorage.getItem("userName") === null) {
            if (uuid) {
                return <Redirect to={`/name/${uuid}?identity=${identity}`}  />;
            } else {
                return <Redirect to={`/name/?identity=${identity}`}/>;
            }
        } else if (uuid && userId) {
            return <Redirect to={url} />;
        }
        return <LoadingPage/>;
    }
Example #7
Source File: SearchButton.tsx    From nosgestesclimat-site with MIT License 6 votes vote down vote up
export default function SearchButton({ invisibleButton }: SearchButtonProps) {
	const [visible, setVisible] = useState(false)

	useKeypress(
		'k',
		true,
		(e) => {
			e.preventDefault()
			setVisible(true)
		},
		'keydown',
		[]
	)

	const close = () => setVisible(false)

	return visible ? (
		<Redirect to="/documentation" />
	) : (
		<button
			className="ui__ simple small button"
			css={invisibleButton ? 'display: none !important' : ''}
			onClick={() => setVisible(true)}
		>
			{emoji('?')} <Trans>Rechercher</Trans>
		</button>
	)
}
Example #8
Source File: Login.tsx    From react-js-tutorial with MIT License 6 votes vote down vote up
LoginComponent: React.FC<Props> = ({ username, login }) => {
  const [name, setName] = useState(username);
  const onSubmit = useCallback(
    async (ev) => {
      ev.preventDefault();
      if (!isEmpty(name)) {
        login(name);
      }
    },
    [name, login]
  );
  return isEmpty(username) ? (
    <form role="form" onSubmit={onSubmit}>
      <label>
        Name:
        <input
          type="text"
          placeholder="Enter your login"
          value={name}
          onChange={(ev) => setName((ev.target as HTMLInputElement).value)}
          required
          minLength={4}
          maxLength={10}
        />
      </label>
      <button>Login</button>
    </form>
  ) : (
    <Redirect to="/ticktacktoe" />
  );
}
Example #9
Source File: App.tsx    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
App: VFC = () => {
  const { hash, pathname } = useLocation();
  const { action } = useHistory();

  useEffect(() => {
    if (!hash || action !== 'POP') {
      window.scrollTo(0, 0);
    }
  }, [action, hash, pathname]);

  return (
    <div className="container">
      <Switch>
        <Route exact path="/">
          <Home />
        </Route>
        <Route path="/characters" component={Characters} />
        <Redirect to="/" />
      </Switch>
    </div>
  );
}
Example #10
Source File: routerUtil.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
// React-Router Redirect component (within domain)
export function RedirectIso(props: { to: string, httpCode?: number }) {
  return (
    <Route
      render={({ staticContext }) => {
        if (windowIso.isSsr && staticContext) {
          (staticContext as StaticRouterContext).statusCode = props.httpCode || 302;
          (staticContext as StaticRouterContext).url = props.to;
        }
        return <Redirect to={props.to} />;
      }}
    />
  );
}
Example #11
Source File: Characters.tsx    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
Characters: VFC<RouteComponentProps> = ({ match }) => (
  <>
    <header>
      <h1>『SLAM DUNK』登場人物</h1>
    </header>
    <Switch>
      <Route exact path={`${match.path}`}>
        <AllCharacters />
      </Route>
      <Route path={`${match.path}/:schoolCode`}>
        <SchoolCharacters />
      </Route>
      <Redirect to="/" />
    </Switch>
    <Divider hidden />
    <HomeButton />
  </>
)
Example #12
Source File: App.tsx    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
App: VFC = () => (
  <>
    <Switch>
      <Route path="/" exact component={Home} />
      <Route path="/:orgCode/members" component={Members} />
      <Redirect to="/" />
    </Switch>
  </>
)
Example #13
Source File: ProtectedRoute.tsx    From flame with MIT License 6 votes vote down vote up
ProtectedRoute = ({ ...rest }: RouteProps) => {
  const { isAuthenticated } = useSelector((state: State) => state.auth);

  if (isAuthenticated) {
    return <Route {...rest} />;
  } else {
    return <Redirect to="/settings/app" />;
  }
}
Example #14
Source File: App.tsx    From useDApp with MIT License 6 votes vote down vote up
export function App() {
  return (
    <Page>
      <GlobalStyle />
      <BrowserRouter>
        <NavBar />
        <Switch>
          <Route exact path="/balance" component={Balance} />
          <Route exact path="/prices" component={Prices} />
          <Route exact path="/ens" component={ENSExample} />
          <Route exact path="/block" component={Block} />
          <Route exact path="/tokens" component={Tokens} />
          <Route exact path="/send" component={SendEtherPage} />
          <Route exact path="/transactions" component={Transactions} />
          <Route exact path="/web3modal" component={Web3Modal} />
          <Route exact path="/web3react" component={Web3ReactConnector} />
          <Route exact path="/multichain" component={Multichain} />
          <Route exact path="/wallet-connect" component={WalletConnect} />
          <Redirect exact from="/" to="/balance" />
        </Switch>
      </BrowserRouter>
      <NotificationsList />
    </Page>
  )
}
Example #15
Source File: PrivateRoute.tsx    From nft-market with MIT License 6 votes vote down vote up
PrivateRoute = ({ component: Component, path }: PrivateRouteProps) => {
  const { isAuthenticated } = useAppState()

  return (
    <Route
      path={path}
      render={props => (isAuthenticated ? <Component {...props} /> : <Redirect to="/" />)}
    />
  )
}
Example #16
Source File: Signup.tsx    From tutorial-cloudflare-bookstore with Apache License 2.0 6 votes vote down vote up
showConfirmationForm = () => {
    // if (this.state.redirect) 
    return <Redirect to="/" />;

    // return (
    //   <form onSubmit={this.onConfirm}>
    //     <FormGroup controlId="confirmationCode">
    //       <ControlLabel>Confirmation code</ControlLabel>
    //       <FormControl
    //         name="code"
    //         type="tel"
    //         bsSize="large"
    //         value={this.state.confirmationCode}
    //         onChange={this.onConfirmationCodeChange}
    //       />
    //       <FormControl.Feedback />
    //       <HelpBlock>
    //         A confirmation code will be sent to the email address provided
    //       </HelpBlock>
    //     </FormGroup>
    //     <Button
    //       block
    //       bsSize="large"
    //       type="submit"
    //       disabled={this.state.confirmationCodeValid === "success"}
    //     >
    //       {this.state.loading && (
    //         <Glyphicon glyph="refresh" className="spinning" />
    //       )}
    //       Confirm
    //     </Button>
    //   </form>
    // );
  };
Example #17
Source File: SearchBar.tsx    From tutorial-cloudflare-bookstore with Apache License 2.0 6 votes vote down vote up
render() {
    return (
      <form className="searchform mainsearch">
        <div className="row">
          <div className="col-md-8 search-padding">
            <div className="input-group">
              <input
                type="text"
                className="form-control no-radius"
                id="txtSearch"
                placeholder="Search"
                value={this.state.value}
                onChange={this.handleChange}
                style={{ width: "5vw" }}
              />
              <div style={{ display: "flex", flexDirection: "row" }}>
                <button
                  className="btn btn-orange no-radius"
                  onClick={this.onSearch}
                >
                  <div
                    style={{
                      fontSize: "14px",
                      color: "#ffffff",
                      fontWeight: "bold",
                    }}
                  >
                    Search
                  </div>
                </button>
              </div>

              {this.state.redirect && <Redirect to={this.state.redirect} />}
            </div>
          </div>
        </div>
      </form>
    );
  }
Example #18
Source File: CheckoutConfirm.tsx    From tutorial-cloudflare-bookstore with Apache License 2.0 6 votes vote down vote up
render() {
    if (this.state.toPastOrders) return <Redirect to='/past' />

    return (
      <div>
        <CategoryNavBar />
        <div className="well-bs">
          <div className="white-box no-margin-top no-margin-bottom">
            <h3>Purchase confirmed</h3>
          </div>
        </div>
        <div className="well-bs full-page no-padding-bottom no-padding-top">
          <div className="white-box padding-50 no-margin-top col-md-12 no-margin-bottom">
            <h4 className="text-center">Your purchase is complete!</h4>
            <button className="btn btn-black btn-black-center" type="button" onClick={this.onViewReceipt}>View Receipt</button>
          </div>
          <div className="no-margin-top no-padding">
            <a href="/best"><img src={bestSellers} alt="Best sellers" className="checkout-img no-padding" /></a>
            <a href="/past"><img src={pastOrders} alt="Past orders" className="checkout-img no-padding" /></a>
          </div>
        </div>
      </div>
    );
  }
Example #19
Source File: ShoppingCart.tsx    From tutorial-cloudflare-bookstore with Apache License 2.0 6 votes vote down vote up
render() {
    if (this.state.toCheckout) return <Redirect to="/checkout" />;

    return this.state.isLoading ? (
      <div className="loader"></div>
    ) : (
      <div className="Category">
        <CategoryNavBar />
        <div className="well-bs padding-bottom-120">
          <div className="white-box no-margin-top">
            <h3>Shopping cart</h3>
          </div>
          {this.state.orders.map((order) => (
            <CartProductRow
              order={order.order}
              book={order.book}
              key={order.order.bookId}
              calculateTotal={() => this.getOrderTotal(true)}
            />
          ))}
          <div className="pull-right checkout-padding">
            <button
              className="btn btn-black"
              type="button"
              disabled={this.state.orders.length < 1}
              onClick={this.onCheckout}
            >
              Checkout
            </button>
          </div>
        </div>
        <div className="well-bs col-md-12 full-page"></div>
      </div>
    );
  }
Example #20
Source File: Search.tsx    From clarity with Apache License 2.0 6 votes vote down vote up
Results = observer((props: { container: SearchContainer }) => {
  const result = props.container.result;
  if (result == null) return null;

  if (typeof result === 'string') return <ErrorMessage error={result} />;

  if ('block' in result) {
    const getBlockResult = result as GetBlockResult,
      hash = getBlockResult.block?.hash;
    return <Redirect to={Pages.block(hash!)} />;
  }

  if ('deploy' in result) {
    const getDeployResult = result as GetDeployResult,
      hash = getDeployResult.deploy.hash;
    return <Redirect to={Pages.deploy(hash)} />;
  }

  return <ErrorMessage error={`Don't know how to display ${typeof result}`} />;
})
Example #21
Source File: SwitchView.tsx    From electron with MIT License 5 votes vote down vote up
SwitchViewHome = () => (
  <PackingWithAuth>
    <Route path="/home/" exact component={() => <Redirect to="/home/list" />}></Route>
    <Route path="/home/list" component={lazy(() => import('@/Render/pages/Home/index'))}></Route>
    <Route path="/home/info" component={lazy(() => import('@/Render/pages/Home/index'))}></Route>
  </PackingWithAuth>
)
Example #22
Source File: MigrateV1Exchange.tsx    From sushiswap-exchange with GNU General Public License v3.0 5 votes vote down vote up
export default function MigrateV1Exchange({
  history,
  match: {
    params: { address }
  }
}: RouteComponentProps<{ address: string }>) {
  const validatedAddress = isAddress(address)
  const { chainId, account } = useActiveWeb3React()

  const exchangeContract = useV1ExchangeContract(validatedAddress ? validatedAddress : undefined)
  const tokenAddress = useSingleCallResult(exchangeContract, 'tokenAddress', undefined, NEVER_RELOAD)?.result?.[0]

  const token = useToken(tokenAddress)

  const liquidityToken: Token | undefined = useMemo(
    () =>
      validatedAddress && chainId && token
        ? new Token(chainId, validatedAddress, 18, `UNI-V1-${token.symbol}`, 'Uniswap V1')
        : undefined,
    [chainId, validatedAddress, token]
  )
  const userLiquidityBalance = useTokenBalance(account ?? undefined, liquidityToken)

  // redirect for invalid url params
  if (!validatedAddress || tokenAddress === AddressZero) {
    console.error('Invalid address in path', address)
    return <Redirect to="/migrate/v1" />
  }

  return (
    <BodyWrapper style={{ padding: 24 }}>
      <AutoColumn gap="16px">
        <AutoRow style={{ alignItems: 'center', justifyContent: 'space-between' }} gap="8px">
          <BackArrow to="/migrate/v1" />
          <TYPE.mediumHeader>Migrate V1 Liquidity</TYPE.mediumHeader>
          <div>
            <QuestionHelper text="Migrate your liquidity tokens from Uniswap V1 to SushiSwap LP Token." />
          </div>
        </AutoRow>

        {!account ? (
          <TYPE.largeHeader>You must connect an account.</TYPE.largeHeader>
        ) : validatedAddress && chainId && token?.equals(WETH[chainId]) ? (
          <>
            <TYPE.body my={9} style={{ fontWeight: 400 }}>
              Because SushiSwap LP Token uses WETH under the hood, your Uniswap V1 WETH/ETH liquidity cannot be migrated. You
              may want to remove your liquidity instead.
            </TYPE.body>

            <ButtonConfirmed
              onClick={() => {
                history.push(`/remove/v1/${validatedAddress}`)
              }}
            >
              Remove
            </ButtonConfirmed>
          </>
        ) : userLiquidityBalance && token ? (
          <V1PairMigration liquidityTokenAmount={userLiquidityBalance} token={token} />
        ) : (
          <EmptyState message="Loading..." />
        )}
      </AutoColumn>
    </BodyWrapper>
  )
}
Example #23
Source File: MigrateV1Exchange.tsx    From luaswap-interface with GNU General Public License v3.0 5 votes vote down vote up
export default function MigrateV1Exchange({
  history,
  match: {
    params: { address }
  }
}: RouteComponentProps<{ address: string }>) {
  const validatedAddress = isAddress(address)
  const { chainId, account } = useActiveWeb3React()

  const exchangeContract = useV1ExchangeContract(validatedAddress ? validatedAddress : undefined)
  const tokenAddress = useSingleCallResult(exchangeContract, 'tokenAddress', undefined, NEVER_RELOAD)?.result?.[0]

  const token = useToken(tokenAddress)

  const liquidityToken: Token | undefined = useMemo(
    () =>
      validatedAddress && chainId && token
        ? new Token(chainId, validatedAddress, 18, `LUA-V1-${token.symbol}`, 'LuaSwap LP Token V1')
        : undefined,
    [chainId, validatedAddress, token]
  )
  const userLiquidityBalance = useTokenBalance(account ?? undefined, liquidityToken)

  // redirect for invalid url params
  if (!validatedAddress || tokenAddress === AddressZero) {
    console.error('Invalid address in path', address)
    return <Redirect to="/migrate/v1" />
  }

  return (
    <BodyWrapper style={{ padding: 24 }}>
      <AutoColumn gap="16px">
        <AutoRow style={{ alignItems: 'center', justifyContent: 'space-between' }} gap="8px">
          <BackArrow to="/migrate/v1" />
          <TYPE.mediumHeader>Migrate V1 Liquidity</TYPE.mediumHeader>
          <div>
            <QuestionHelper text="Migrate your liquidity tokens from LuaSwap V1 to LuaSwap V2." />
          </div>
        </AutoRow>

        {!account ? (
          <TYPE.largeHeader>You must connect an account.</TYPE.largeHeader>
        ) : validatedAddress && chainId && token?.equals(WETH[chainId]) ? (
          <>
            <TYPE.body my={9} style={{ fontWeight: 400 }}>
              Because LuaSwap V2 uses WETH under the hood, your LuaSwap V1 WETH/ETH liquidity cannot be migrated. You
              may want to remove your liquidity instead.
            </TYPE.body>

            <ButtonConfirmed
              onClick={() => {
                history.push(`/remove/v1/${validatedAddress}`)
              }}
            >
              Remove
            </ButtonConfirmed>
          </>
        ) : userLiquidityBalance && token ? (
          <V1PairMigration liquidityTokenAmount={userLiquidityBalance} token={token} />
        ) : (
          <EmptyState message="Loading..." />
        )}
      </AutoColumn>
    </BodyWrapper>
  )
}
Example #24
Source File: RemoveV1Exchange.tsx    From luaswap-interface with GNU General Public License v3.0 5 votes vote down vote up
export default function RemoveV1Exchange({
  match: {
    params: { address }
  }
}: RouteComponentProps<{ address: string }>) {
  const validatedAddress = isAddress(address)
  const { chainId, account } = useActiveWeb3React()

  const exchangeContract = useV1ExchangeContract(validatedAddress ? validatedAddress : undefined, true)
  const tokenAddress = useSingleCallResult(exchangeContract, 'tokenAddress', undefined, NEVER_RELOAD)?.result?.[0]
  const token = useToken(tokenAddress)

  const liquidityToken: Token | undefined = useMemo(
    () =>
      validatedAddress && chainId && token
        ? new Token(chainId, validatedAddress, 18, `LUA-V1-${token.symbol}`, 'LuaSwap LP Token V1')
        : undefined,
    [chainId, validatedAddress, token]
  )
  const userLiquidityBalance = useTokenBalance(account ?? undefined, liquidityToken)

  // redirect for invalid url params
  if (!validatedAddress || tokenAddress === AddressZero) {
    console.error('Invalid address in path', address)
    return <Redirect to="/migrate/v1" />
  }

  return (
    <BodyWrapper style={{ padding: 24 }} id="remove-v1-exchange">
      <AutoColumn gap="16px">
        <AutoRow style={{ alignItems: 'center', justifyContent: 'space-between' }} gap="8px">
          <BackArrow to="/migrate/v1" />
          <TYPE.mediumHeader>Remove V1 Liquidity</TYPE.mediumHeader>
          <div>
            <QuestionHelper text="Remove your LuaSwap V1 liquidity tokens." />
          </div>
        </AutoRow>

        {!account ? (
          <TYPE.largeHeader>You must connect an account.</TYPE.largeHeader>
        ) : userLiquidityBalance && token && exchangeContract ? (
          <V1PairRemoval
            exchangeContract={exchangeContract}
            liquidityTokenAmount={userLiquidityBalance}
            token={token}
          />
        ) : (
          <EmptyState message="Loading..." />
        )}
      </AutoColumn>
    </BodyWrapper>
  )
}
Example #25
Source File: Wizard.tsx    From twilio-voice-notification-app with Apache License 2.0 5 votes vote down vote up
Wizard = ({ data, activeStep }: StepProps) => {
  // Info about completition status of each step.
  const stepsCompletion = useSelector(stepsCompletionSelector);

  return (
    <Box>
      <Stepper
        activeStep={activeStep && routerSteps.indexOf(activeStep)}
        alternativeLabel
        connector={<CustomConnector />}
        style={{ backgroundColor: 'transparent' }}
      >
        {routerSteps.map((step) => {
          const { label } = step;
          const completed =
            !isStepAhead(activeStep, step) && stepsCompletion[step.key];

          return (
            <Step key={label} disabled={true}>
              <StepButton
                icon={
                  <WizardStepIcon
                    icon={step.icon}
                    active={activeStep === step}
                    completed={completed}
                  />
                }
              >
                <StyledStepLabel>{label}</StyledStepLabel>
              </StepButton>
            </Step>
          );
        })}
      </Stepper>
      <Switch>
        {routerSteps.map((step) => (
          <Route
            key={step.key}
            path={step.location}
            render={() => React.createElement(step.component, { step, data })}
          />
        ))}
        <Redirect from="*" to="/create/configure" />
      </Switch>
    </Box>
  );
}
Example #26
Source File: IndexPage.tsx    From disco-cube-admin with MIT License 5 votes vote down vote up
IndexPage: React.FC<Props> = ({}) => {
  const { user } = useStore(authStore);
  if (!user) return <Redirect to={routes.login.path()} />;
  return <Redirect to={routes.stats.path()} />;
}
Example #27
Source File: SignMessagePage.tsx    From clarity with Apache License 2.0 5 votes vote down vote up
render() {
    if (this.props.signMessageContainer.toSignMessage) {
      return (
        <div style={{ flexGrow: 1 }}>
          <Typography align={'center'} variant={'h5'}>
            Your signature is being requested
          </Typography>

          <Box mt={4} mb={3}>
            {this.props.authContainer.selectedUserAccount && (
              <Typography variant={'h6'}>
                Active key:&nbsp;
                {this.props.authContainer.selectedUserAccount.name}
              </Typography>
            )}
            <Typography variant={'h6'}>Deploy hash (base16):</Typography>
            <Typography style={{ wordBreak: 'break-all' }}>
              {this.props.signMessageContainer.toSignMessage!.data}
            </Typography>
          </Box>
          <Box mt={8}>
            <Grid
              container
              spacing={4}
              justify={'center'}
              alignItems={'center'}
            >
              <Grid item>
                <Button
                  variant="contained"
                  color="secondary"
                  onClick={() => {
                    this.props.signMessageContainer.cancel();
                  }}
                >
                  Cancel
                </Button>
              </Grid>
              <Grid item>
                <Button
                  onClick={() => this.props.signMessageContainer.signMessage()}
                  variant="contained"
                  color="primary"
                >
                  Sign
                </Button>
              </Grid>
            </Grid>
          </Box>
        </div>
      );
    } else {
      return <Redirect to={Pages.Home} />;
    }
  }
Example #28
Source File: AuthRequired.tsx    From disco-cube-admin with MIT License 5 votes vote down vote up
AuthRequired: React.FC<Props> = ({}) => {
  const { user } = useStore(authStore);
  if (!user) return <Redirect to={routes.login.path()} />;
  return null;
}
Example #29
Source File: RemoveV1Exchange.tsx    From cheeseswap-interface with GNU General Public License v3.0 5 votes vote down vote up
export default function RemoveV1Exchange({
  match: {
    params: { address }
  }
}: RouteComponentProps<{ address: string }>) {
  const validatedAddress = isAddress(address)
  const { chainId, account } = useActiveWeb3React()

  const exchangeContract = useV1ExchangeContract(validatedAddress ? validatedAddress : undefined, true)
  const tokenAddress = useSingleCallResult(exchangeContract, 'tokenAddress', undefined, NEVER_RELOAD)?.result?.[0]
  const token = useToken(tokenAddress)

  const liquidityToken: Token | undefined = useMemo(
    () =>
      validatedAddress && chainId && token
        ? new Token(chainId, validatedAddress, 18, `UNI-V1-${token.symbol}`, 'Uniswap V1')
        : undefined,
    [chainId, validatedAddress, token]
  )
  const userLiquidityBalance = useTokenBalance(account ?? undefined, liquidityToken)

  // redirect for invalid url params
  if (!validatedAddress || tokenAddress === AddressZero) {
    console.error('Invalid address in path', address)
    return <Redirect to="/migrate/v1" />
  }

  return (
    <BodyWrapper style={{ padding: 24 }} id="remove-v1-exchange">
      <AutoColumn gap="16px">
        <AutoRow style={{ alignItems: 'center', justifyContent: 'space-between' }} gap="8px">
          <BackArrow to="/migrate/v1" />
          <TYPE.mediumHeader>Remove V1 Liquidity</TYPE.mediumHeader>
          <div>
            <QuestionHelper text="Remove your Uniswap V1 liquidity tokens." />
          </div>
        </AutoRow>

        {!account ? (
          <TYPE.largeHeader>You must connect an account.</TYPE.largeHeader>
        ) : userLiquidityBalance && token && exchangeContract ? (
          <V1PairRemoval
            exchangeContract={exchangeContract}
            liquidityTokenAmount={userLiquidityBalance}
            token={token}
          />
        ) : (
          <EmptyState message="Loading..." />
        )}
      </AutoColumn>
    </BodyWrapper>
  )
}