Search code examples
javascriptreactjsreact-router-dom

How to use either react router useParams() or window.localStorage()


In my scenario , the component should take a value either from the URL or from localStorage but when I attempt to get value from useParams() it throws this error:

Uncaught ReferenceError: useParams is not defined

My code is:

const { userId } = useParams() || props;

Solution

  • I think you didn't import useParams, in which case do so at the top of your file :

    import {useParams} from "react-router-dom"
    

    Then do :

    let {userId} = useParmas();
    if(!userId) userId = props.userId;
    

    Because useParams return an object, an empty object like so {} if there isn't any parameter, but {} is not false, so by doing so useParams() || props, if there isn't an userId parameter in you your url, you will always get undefined.