Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting using useEffect hook

The idea is that I've got a component that renders something but in the meantime is checking something that will return or redirect to another component:

useEffect(() => {
  (() => {
    if (true) {
      // return to one component
    }

    // return to another component
  })();
});

return (
  <div> Javier </div>
);

I think that it is possible using the useEffect hook, but the problem is that, it does not redirect to my components, I tried using Redirect from the react-router, returning the component itself, and also using the history package, in this case, only replaced the url but no redirection at all.

Is this possible? Or maybe I'm way off the point.

Thanks a lot!

like image 825
jvrdom Avatar asked Oct 18 '19 04:10

jvrdom


3 Answers

if you are just needing conditional rendering you could do something like this:

const LoadingComponent = () => <div> Javier </div>

function Landing(props) {
    const [state={notLoaded:true}, setState] = useState(null);
    useEffect(() => {
        const asyncCallback = async () =>{
            const data = await axios.get('/someApiUrl')
            setState(data)
        }

        asyncCallback()
    },[]);

    if(!state){
        return <FalseyComponent />
    }
    if(state.notLoaded){
        //return some loading component(s) (or nothing to avoid flicker)
        return <LoadingComponent /> // -or- return <div/>
    }
    return <TruthyComponent />
}

or redirect completely:

const LoadingComponent = () => <div> Javier </div>

function Landing(props) {
    const [state={notLoaded:true}, setState] = useState(null);
    useEffect(() => {
        const asyncCallback = async () =>{
            const data = await axios.get('/someApiUrl')
            setState(data)
        }

        asyncCallback()
    },[]);

    if(!state){
        return <Redirect to='/falseyRoute' />
    }
    if(state.notLoaded){
        //return some loading component(s) or (nothing to avoid flicker)
        return <LoadingComponent /> // -or- return <div/>
    }
    return <Redirect to='/truthyRoute' />
}
like image 87
Willman.Codes Avatar answered Oct 20 '22 01:10

Willman.Codes


Using React router v6 you can create a redirection using useEffect:

import React, { useEffect } from 'react';
import {
  BrowserRouter, Route, Routes, useNavigate,
} from 'react-router-dom';

const App = () => (
  <div>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Main />} />
        <Route path="/home" element={<Home />} />
      </Routes>
    </BrowserRouter>
  </div>
);

const Main = () => {
  const navigate = useNavigate();
  useEffect(() => {
    let didCancel = false;
    const goToHomePage = () => navigate('/home');
    if (!didCancel) { goToHomePage(); }
    return () => { didCancel = true; };
  }, [navigate]);
  return (
    <div>
      <h1>Welcome Main!</h1>
    </div>
  );
};

const Home = () => (
  <div>
    <h1>Welcome Home!</h1>
  </div>
);

export default App;

If you want to create an alternative redirection to another component, you can do it as below:

import React, { useEffect } from 'react';
import {
  BrowserRouter, Route, Routes, useNavigate,
} from 'react-router-dom';

const App = () => (
  <div>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Main />} />
        <Route path="/home" element={<Home />} />
        <Route path="/other" element={<Other />} />
      </Routes>
    </BrowserRouter>
  </div>
);

const Main = () => {
  const navigate = useNavigate();
  useEffect(() => {
    let didCancel = false;
    const goToHomePage = () => navigate('/home');
    const goToOtherPage = () => navigate('/other');
    if (!didCancel) { goToHomePage(); } else { goToOtherPage(); }
    return () => { didCancel = true; };
  }, [navigate]);
  return (
    <div>
      <h1>Welcome Main!</h1>
    </div>
  );
};

const Home = () => (
  <div>
    <h1>Welcome Home!</h1>
  </div>
);

const Other = () => (
  <div>
    <h1>Welcome Other!</h1>
  </div>
);

export default App;

In React router 5 with changed old syntax it should also work. However, in React router 6 I did not find Redirect so the above redirection is more useful.

like image 22
Andrzej Avatar answered Oct 20 '22 01:10

Andrzej


Try to return based on some state value like this.

import { Redirect } from "react-router-dom"; //import Redirect first

const [redirctTo, setRedirctTo] = useState(false); // your state value to manipulate

useEffect(() => {
  (() => {
    if (true) {
      setRedirctTo(true)
    }

    // return to another component
  })();
});

if(redirctTo){
  return <Redirect to="/your-url" />
} else {
  return (
  <div> Javier </div>
);
}

like image 36
coderLogs Avatar answered Oct 19 '22 23:10

coderLogs