Home > Software design >  What is the equivalent of 'match' in the new react version
What is the equivalent of 'match' in the new react version

Time:08-03

function ProductScreen() {
  const dispatch = useDispatch()
  const productDetails = useSelector(state => state.productDetails)
  const { loading, error, product } = productDetails

  const { id } = useParams()

  useEffect(() => {
    dispatch(listProductDetails((id)))

  }, [dispatch, match])

In this code in the end I used to pass match in useEffect in the end. I know I can't do this anymore in the new version so what is the equivalent to match now?

CodePudding user response:

If by "match" you mean the match object that was a RRDv5 route prop used to access the route path params, i.e. props.match.params.id then there is no equivalent in RRDv6. There are no route props in RRDv6. If you need to access the route path params use the useParams hook.

Based on the code snippet you are already using the useParams hook and have accessed the id route path parameter. It appears that id is a dependency in the useEffect hook since it is referenced inside the callback, so it should be added to the useEffect hook's dependency array.

Example:

function ProductScreen() {
  const dispatch = useDispatch();

  const { loading, error, product } = useSelector(state => state.productDetails);

  const { id } = useParams();

  useEffect(() => {
    dispatch(listProductDetails((id))); // <-- id referenced here
  }, [dispatch, id]); // <-- should list as dependency here

  ...

The useEffect hook's callback will be called on the initial render, and when values in the dependency array update the hook's callback will be triggered again. For this reason it's sometimes necessary to do a check that the dependency value is valid.

Example:

const { id } = useParams();

useEffect(() => {
  if (id) {
    // only dispatch action if id is truthy
    dispatch(listProductDetails((id)));
  }
}, [dispatch, id]);
  • Related