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

164
Visualizações
React - clicking on a router link before the link gets a value

the issue is that url change happens before the link gets a value. i'm receiving the state directly through the component, but before that happens, the component is already clicked. the value gets assigned after url change, so it returns undefined. how would i fix this?

import React, {useEffect, useState} from "react";
import "./Main.scss";
import CategoryWindow from "./CategoryWindow"
import RecipeSelection from "./RecipeSelection";
import RecipeWindow from "./RecipeWindow";
import {BrowserRouter as Router,  Switch, Route, Link} from "react-router-dom";


const Main =()=> {
    const [showElement, setShowElement] = useState("category");
    const [selectedCategory, setSelectedCategory] = useState();

    useEffect(()=> {
       if (selectedCategory) {
           setShowElement("recipeSelection")
       }
    });

    return (
    <>
        <main className="main">
        <Router>
            <div>
                <div>
                    {showElement === "category" ?
                        <Link to={`/${selectedCategory}`}>
                            <CategoryWindow
                                passSelectedCategory={setSelectedCategory}
                            />
                        </Link>
                        : ''}
                </div>
            </div>
        </Router>
        </main>
    </>
    )
}

export default Main;

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

try changing the useEffect to this so it will not rerender every millisecond and can you show how CategoryWindow looks like?

useEffect(()=> {
   if (selectedCategory) {
       setShowElement("recipeSelection")
   }
}, [selectedCategory]);

i don't think a Link should be putted directly in a Router but if you want to get the category from the link into the CategoryWindow component you can get it directly from the link without passing the state selectedCategory

Main.js

<>
   <Router>
      <Route path="item">
          <Route path=":category" element={<CategoryWindow />}/>}
      </Route>
      <Route path="/" element={<Component />}/>}
   </Router>
</>

CategoryWindow.js

import { useParams} from 'react-router-dom';

const { category} = useParams()
<>
   <div>{category}</div> // this is the actual selectedCategory
</>

Component.js

const [selectedCategory, setSelectedCategory] = useState();
<>
   <Link to={"/category/" + selectedCategory}/>
</>
about 4 years ago · Santiago Trujillo Relatório

0

pass [selectedCategory] as the second argument in useEffect.

 useEffect(()=> {
           if (selectedCategory) {
               setShowElement("recipeSelection")
           }
        },[selectedCategory]);

check this: Using the Effect Hook

about 4 years ago · Santiago Trujillo 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