Home > other >  React - clicking on a router link before the link gets a value
React - clicking on a router link before the link gets a value

Time:04-23

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;

CodePudding user response:

pass [selectedCategory] as the second argument in useEffect.

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

check this: Using the Effect Hook

CodePudding user response:

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}/>
</>
  • Related