How to refresh component after queryParam was removed React

Viewed 27

I have page (create request) with form which have path requests/request. After save form is redirected page to detail of that request with path requests/request?id=1.

When i try go to create request page by navigation menu button from detail of created request, queryParam is removed (I have again requests/request), but page is not refreshed to default state and some data stay loaded at component.

When i redirect from another page to create request page is component loaded at default state. Create request and detail of request is one component.

When i go from detail page (requests/request?id=1) I want to have create request page (requests/request) at default state like when i go from another page.

Can you help me what i do wrong ?

1 Answers

You will need to use a useEffect hook with a dependency on the id queryString parameter to issue any side-effect when the id value updates.

Example:

import { useSearchParams } from 'react-router-dom';

...

const [searchParams, setSearchParams] = useSearchParams();
const id = searchParams.get("id");

useEffect(() => {
  // logic to run when id value updates
}, [id]);

An alternative is to create a wrapper component that "sniffs" the id query parameter and uses it as a React key on the routed component. This will remount the routed component when the key, i.e. id, value changes.

Example:

import { useSearchParams } from 'react-router-dom';

const RequestWrapper = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const id = searchParams.get("id");

  return <Request key={id}> ..... />;
}

...

<Routes>
  ...
  <Route path="/requests/request" element={<RequestWrapper />} />
  ...
</Routes>
Related