1

I am doing a url shortner project. In this project i am storing the webpages to database and redirect to the webpage on entering the url(url will be always valid) in address bar.

I am trying to redirect my given to external website using the following code

import { getUrl } from "../apis/api";
import React, { useState } from "react";

const RedirectPage =  () => {

    const [longUrl, setLongUrl] = useState("");
    // const [location,setLocation] = useState("");


    const getLink = async (stringUrl) => {
        var vlongUrl= await getUrl({stringUrl});
        if(vlongUrl){
            setLongUrl(vlongUrl);
        }
    };


    var stringUrl= window.location.pathname ;
    if(stringUrl.length!==0){
        stringUrl = stringUrl.substring(1);
        getLink(stringUrl);
    }else{
        window.location='http://localhost:3000/app';                   // Go to not found page
        return null;
    }


    if(longUrl=== "NOT FOUND"){
        window.location='http://localhost:3000/notfound';              // Go to not found page
        return null;
    }else{
        window.location.assign(longUrl);
        return null;
    }

    // return (
    //     <h5>Redirect to <a href= {longUrl} > {longUrl} </a> </h5>
    // );

}

export default RedirectPage;

But it is not behaving as i wanted where i am getting wrong.

Below is app.js code

import React from "react";
import { BrowserRouter, Routes, Route} from "react-router-dom";

import AppPage from "./pages/AppPage";
import NotFound from "./pages/NotFound";
import RedirectPage from "./pages/RedirectPage";

function App() {

  return (
    <>
      <BrowserRouter>
        <Routes>
          {/* <Route exact path="/" element={<AppPage />}></Route> */}
          <Route exact path="/app" element={<AppPage />}></Route>
          <Route exact path="/notfound" element={<NotFound />}></Route>
           <Route exact path="/*" element={<RedirectPage />}></Route>
        </Routes>
      </BrowserRouter>
    </>
  );

}

export default App;

Error: enter image description here

Url get changed to :

http://localhost:3000/[object%20Object]

If i comment out redirect i am getting valid url in html.

enter image description here

randomUser
  • 653
  • 6
  • 23

1 Answers1

1

You should be doing these check / api call only when path changes. So use useEffect with dependency.

var stringUrl = window.location.pathname ;
useEffect(() => {
    if(stringUrl.length!==0) {
        stringUrl = stringUrl.substring(1);
        getLink(stringUrl);
    } else {
        window.location='http://localhost:3000/app';
        return null;
    }
}, [stringUrl]);
Arun Kumar
  • 355
  • 3
  • 10