1

I have a url like this "http://localhost:3000/MockApi/getDetails/A1B@$CZSK_2"

I want to hide "A1B@$CZSK_2" part from the URL.

When above URL clicked it will be go to this component

import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import React, { useEffect, useState } from 'react';
import { useParams , } from 'react-router-dom';

function App() {
  const [data, setData] = useState<any>(null);
  const { key } = useParams();
  
  useEffect(() => {
    const apiUrl = `http://localhost:8080/MockApi/getDetails/${key}`;
    fetch(apiUrl)
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then(data => {
        // Handle the API response data
        setData(data);
        console.log(data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, [key]);

  return (
    <div className="container col-12 col-md-3 mt-5 ">
      <div>
        <div className="row justify-content-center border border-secondary p-3 rounded text-center shadow">
          <div className="col-md-7">
            <h2 className="text-center">ABC Company</h2>
            <form className="mt-3 text-center">
              <div className='container'>
                {data && <h4 className="text-center pt-5">MSISDN: {data.msisdn}</h4>}
                {data && <h4 className="text-center pt-5">ServerRef: {data.severRef}</h4>}   
              </div>
  
              <div className="mb-3 pt-5 text-center">
                <input
                  type="text"
                  name="OTP"
                  className="form-control"
                  placeholder="OTP"
                />
              </div>
              <button type="submit" className="btn btn-primary w-100">
                Submit
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}
  
export default App;

when this component display in the browser I need to hide "A1B@$CZSK_2" part from URL in the address bar and need to stay in the same page which is the App component only need to hide the url key ("A1B@$CZSK_2")

This is how routes look like:

import './App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import {BrowserRouter as Routes, Route, Router } from 'react-router-dom';
import Home from './home';

function MainApp() {
  return (
    <div className="App">
    <Router basename='/api' location={"/"} navigator={}>
        <Routes>
          <Route path="/MockApi/getDetails/:key" element={<Home />} />
        </Routes>
      </Router>
    </div>
  );
}

export default MainApp;

I used MemoryRouter, useNavigate, and useHistroy, none worked for me.

2

1 Answer 1

1

My suggestion here would be to make the key segment optional (using the "?" on the segment), and in the routed component to redirect to "/MockApi/getDetails" as soon as the key parameter has been consumed.

Example:

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './home';

function MainApp() {
  return (
    <div className="App">
      <Router basename='/api'>
        <Routes>
          <Route path="/MockApi/getDetails/:key?" element={<Home />} />
        </Routes>
      </Router>
    </div>
  );
}

export default MainApp;
import './App.css';
import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';

function App() {
  const navigate = useNavigate();
  const { key } = useParams();

  const [data, setData] = useState<any>(null);  
  
  useEffect(() => {
    if (key) {
      navigate("/MockApi/getDetails", { replace: true });

      const apiUrl = `http://localhost:8080/MockApi/getDetails/${key}`;
      fetch(apiUrl)
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          // Handle the API response data
          setData(data);
          console.log(data);
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
    }
  }, [key]);

  return (
    ...
  );
}
  
export default App;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.