Home > front end >  How to use either react router useParams() or window.localStorage()
How to use either react router useParams() or window.localStorage()

Time:01-17

In my scenario , the component should take a value either in the URL or a locale storage but when I attempt to get value from useParams() it throw an error:

Uncaught ReferenceError: useParams is not defined

Really how can I handle this error ?

My code is:

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

How can I fix it?

CodePudding user response:

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.

CodePudding user response:

Make sure that you have imported useParams. If you have imported it already, then try doing this.

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

CodePudding user response:

If you are using a class component, you must use withRouter() instead.

import { withRouter } from "react-router";


class Whatever extends Component {
  render() {
    const { userId } = this.props.match.params;
    return null;
  }
}
  •  Tags:  
  • Related