Search code examples
reactjsundefinedurl-parameters

React useParams returning undefined


I'm building a search engine using the Marvel API. I have a HeroComics component and a Home component. I'm trying to pass {character.name} from HeroComics to Home using the following code in HeroComics:

<ul>
  {data.characters.items.length &gt; 0 ? data.characters.items.map(character =&gt; (
  <li>{character.name}</li>)) : "No characters available"}
</ul>

Here is the relevant code from Home:

    let { heroLinkName } = useParams();

    const [heroName, setHeroName] = useState("");
    const [heroes, setHeroes] = useState([]);
    const [hero, setHero] = useState([]);

    const [show, setShow] = useState(false);

    const handleClose = () => setShow(false);

    const buttonNameRef = useRef();

    useEffect(() => {
        localStorage.setItem('heroName', heroLinkName);
        const heroName = localStorage.getItem('heroName');
        setHeroName(heroName);
        handleClick(heroName);
    }, []);

The hero name (as a string) is supposed to pass from HeroComics to Home and go into local storage as 'heroName' and then pulled from local storage as 'const heroName' and then set to the input value and clicked, but the search input is showing undefined.

enter image description here

How can I fix this issue and get the input to display the actual value that is being passed? Is this happening because the value is a string and not a number because it was working fine on other pages when I'm using numbers.


Solution

  • I think you should change your

    let { heroLinkName } = useParams();
    

    to

    let { name } = useParams();