0

Hi i want to redirect user to "/home" after load() request completes. but how do i redirect the user to "/home" only if he is not currently in "/home" url.

below is my code,

function useAnother(Id: string) {
    const [compId, setCompId] = React.useState(undefined);
    const {setIsLoading} = React.useContext(LoadingContext);
    const comp = useCurrentComp(Id);
    const load = useLoad();
    if (comp && comp.id !== compId) {
        setCompId(comp.id);
        const prevCompId = compId !== undefined;
        if (prevCompId) {
            setIsLoading(true);
            load().then(() => {// how do i check here if user is already in "/home"  //url and then only redirect him to /home 
                history.push("/home"); 
            });
        }
    }
}

could someone help me with this. thanks.

saritha
  • 619
  • 2
  • 12
  • 25

2 Answers2

1

You can react-router's very own hook useLocation

function useAnother(Id: string) {
    const [compId, setCompId] = React.useState(undefined);
    const {setIsLoading} = React.useContext(LoadingContext);
    const localtion = useLocation();
    const comp = useCurrentComp(Id);
    const load = useLoad();

    if (comp && comp.id !== compId) {
        setCompId(comp.id);
        const prevCompId = compId !== undefined;
        if (prevCompId) {
            setIsLoading(true);
            load().then(() => {
                if (location[pathname] !== "/home") history.push("/home"); 
            });
        }
    }
}
Shravan Dhar
  • 1,455
  • 10
  • 18
0

You can check if the window.location.pathname is equal to '/home'. If it is, don't redirect, otherwise redirect.

function useAnother(Id: string) {
    const [compId, setCompId] = React.useState(undefined);
    const {setIsLoading} = React.useContext(LoadingContext);
    const comp = useCurrentComp(Id);
    const load = useLoad();
    if (comp && comp.id !== compId) {
        setCompId(comp.id);
        const prevCompId = compId !== undefined;
        if (prevCompId) {
            setIsLoading(true);
            load().then(() => {// how do i check here if user is already in "/home"  //url and then only redirect him to /home 
                if (window.location.pathname !== "/home"){
                   history.push("/home"); 
                }
            });
        }
    }
}
Matt Croak
  • 2,788
  • 2
  • 17
  • 35