Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
React add a Route after page has loaded

I have an API with a list of names (which could change) I then want to create routes from that list but I keep getting route not found error. However when manually adding the route for a name it works. How do I add a route after the page has loaded to make it work This is my code below

function App() {
    let json =[]
    fetch(`${baseURL}/applications/`).then(response =>{return response.json();}).then(data =>{json=data})
    console.log("json =", json)
    return (
      <Router>
        <div className="App">
          <header className="App-header">
              <Routes>
                  <Route path="/" exact element={<ApplicationsList/>}/>
                  <Route path={"/1080p-Lock"} exact element={<ApplicationPage name={"1080p-Lock"}/>}/>
                  {json.map(item => {ReactDOM.render(<Route path={"/" + item} exact element={<ApplicationPage name={item}/>}/>)})}
              </Routes>
          </header>
        </div>
      </Router>
    );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Issue

The React render function is a synchronous, pure function, it can't wait for asynchronous logic to complete. The json value is reset to an empty array each render cycle.

The route mapping only needs to return the Route components that need to be rendered, using ReactDOM here isn't very valid.

Solution

Use component state to store the fetched data and a mounting useEffect hook to make the fetch request.

function App() {
  const [routes, setRoutes] = useState([]);

  useEffect(() => {
    fetch(`${baseURL}/applications/`)
      .then(response => {
        return response.json();
      })
      .then(data => {
        setRoutes(data);
      })
      .catch(error => {
        // handle any rejected Promises, etc...
      });
  }, []);

  return (
    <Router>
      <div className="App">
        <header className="App-header">
          <Routes>
            <Route path="/" element={<ApplicationsList/>}/>
            <Route path={"/1080p-Lock"} element={<ApplicationPage name={"1080p-Lock"}/>}/>
            {routes.map(item => (
              <Route path={"/" + item} element={<ApplicationPage name={item}/>}/>
            ))}
          </Routes>
        </header>
      </div>
    </Router>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda