d-dripz
d-dripz

Reputation: 85

Get url parameter using URLSearchParams in react

I am trying to grab XSOQSVPbATbRYa94ZuXs from the pid parameter using URLSearchParams.

Here is my URL: http://localhost:3000/edit-product?pid=Z4HLrHGZ1ikKIwlEVkM6

Here is my code:

useEffect(() => {
    if (user) {
      const params = new URLSearchParams(location.search);
      const pid = params.get("pid");

    } else {
      setProducts("");
    }
  }, [user]);

Any idea why I'm receiving the following error: TypeError: Cannot read property 'search' of undefined

Upvotes: 1

Views: 416

Answers (2)

web-sudo
web-sudo

Reputation: 686

location.search won't work. You need to change it by window.location.search

Upvotes: 1

user10876293
user10876293

Reputation:

Where does location.search comes from? unless you destructured it from somewhere, it should be props.location.search if you're using react-router.

Is this question related?

Upvotes: 0

Related Questions