Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router v4 history.push to the same route (different query params) in Functional Component (use Hooks API)

I am trying to code search filter feature for table. I am using react-router-dom v4. When user click search button, I want to navigate page from "/list" to "list?search=abc" by props.history.push(). (I already used RouteComponentProps and withRouter). But I know react-router-dom v4 just changes url while it doesn't not refresh the page. My colleague uses function componentWillReceiveProps in class component to detect query params changes. (now that function is known as getDerivedStateFromProps)

componentWillReceiveProps(nextProps) {
   console.log("next Props");
   if (nextProps.location.search !== this.props.location.search) {
     let parsed = queryString.parse(nextProps.location.
     this.loadData(parsed);
   }

Using React Hook (with Typescript) in functional component is compulsory to me. I tried many ways but it didn't work. Do you know the way to figure this issue out? Thank you very much.

like image 748
hieuht Avatar asked Oct 16 '22 06:10

hieuht


1 Answers

I found my solution, I use useEffect to detect query params search change

useEffect(() => { 
  console.log(`use effect set state search`);
  const searchParams = new URLSearchParams(props.location.search); console.log(search params: ${searchParams}); 
  const search = searchParams.get("search") || "";
  console.log(search: ${search}); setState({ ...state, search: search }); 
  loadData(search); 
}, [props.location.search]);
like image 68
hieuht Avatar answered Oct 20 '22 17:10

hieuht