M
M
miliko mikoyan2019-06-08 20:03:54
React
miliko mikoyan, 2019-06-08 20:03:54

Redirect with history.push not working?

i wrote this code

import React, { FC, Fragment, useEffect } from "react";
import { createBrowserHistory } from "history";
const history = createBrowserHistory();

const HandlerErr: FC<{ error: string }> = ({ error }) => {
  useEffect(()=>{
   const time = setTimeout(() =>  {history.push(`/`)}, 2000);
   return(()=> clearTimeout(time));
  },[error])
  return (
    <Fragment>
      <div>{error}</div>
      <div>{"Contact site administrator"}</div>
    </Fragment>
  );
};

I am using the HandlerErr component for the redirect. but for some reason it doesn't work with history.push (/). vido

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-06-09
@miliko0022

If you are using react-router-dom, then you must use the exact history instance that your router uses.

import React, { FC, useEffect } from 'react';
import { RouteComponentProps, withRouter } from 'react-router-dom';

interface OwnProps {
  error: string;
}

type Props = OwnProps & RouteComponentProps<any>;

const HandlerErr: FC<Props> = ({ error, history }) => {
  useEffect(() => {
   const timeout = setTimeout(() => {
     history.push(`/`);
   }, 2000);
 
   return () => { 
     clearTimeout(timeout);
   };
  }, [error]);

  return (
    <>
      <div>{error}</div>
      <div>Contact site administrator</div>
    </>
  );
};

export default withRouter(HandlerErr);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question