React with Typescript window move to homePage but it restart the data

Viewed 47

I am trying for this component redirect to HomePage but after it is redirected to the home page it restarts the data within.

Any suggestions to replace window.location.href = "/HomePage"?

import React, { useEffect } from "react";

const Thankyou = () => {

    useEffect(() => {
        setTimeout(() => {
            window.location.href = "/HomePage"
        }, 10000)
    }, [])

    return (
        <div className={"movie-container"}>
            <h2>
                Thank you for ordering...<br/>
            </h2>
            <h2>Page will redirect in 10 seconds...</h2>
        </div>
    )
}

export default Thankyou;

These are the Routes for the App.tsx

const App: FC = () => {
    return (
        <>
            <Header/>
            <Routes>
                <Route path="/" element={<Navigate replace to='/HomePage' />} />
                <Route path="/HomePage" element={<HomePage />} />
                <Route path="/FavoritePage" element={<FavoritePage />} />
                <Route path="/MoviePage/movie/:id" element={<MoviePage />} />
                <Route path="/Thankyou" element={<Thankyou />} />
            </Routes>
        </>
    )
};

This is the index.tsx

ReactDOM.render(
    <React.StrictMode>
        <BrowserRouter>
            <GalleryProvider>
                <App />
            </GalleryProvider>
        </BrowserRouter>
    </React.StrictMode>,
    document.getElementById('root')
);
1 Answers

When you mutate window.location.href you end up reloading the app. This effectively remounts the entire app so any React state will be reset.

Use the navigate function to issue an imperative redirect.

import React, { useEffect } from "react";
import { useNavigate } from 'react-router-dom';

const Thankyou = () => {
  const navigate = useNavigate();

  useEffect(() => {
    const timer = setTimeout(() => {
      navigate("/HomePage", { replace: true });
    }, 10000);

    return () => {
      clearTimeout(timer); // <-- clear timeout effect on unmount
    };
  }, [])

  return (
    <div className="movie-container">
      <h2>Thank you for ordering...</h2>
      <h2>Page will redirect in 10 seconds...</h2>
    </div>
  );
};

export default Thankyou;
Related