Search code examples
reactjsreact-routerreact-async

How to rerender function component when id changed in url


I have a React component that fetches some data from IndexedDB that is an asynchronous task it uses the id from the url passed in by the useParams hook, let say id = 1. When I click on the link in the example the id changes to 2 but at this point nothing happens the component does not rerender.

What do I need to do to make it work? I just don't understand why it does not work right now. Can someone enlighten me?

import React, {useState} from 'react';
import { Link, useParams } from "react-router-dom";
import { useAsync } from 'react-async';

export default function (props) {
  let { id } = useParams();

  const { data, error, isLoading } = useAsync({
    promiseFn: loadData,
    id: parseInt(id)
  });

  if (isLoading) return "Loading...";
  if (error) return `Something went wrong: ${error.message}`;
  if (data)
    return (
      <>
        <h1>{data.name}</h1>
        <Link to={'/2'}>other id</Link>
      </>
     );
}

Solution

  • When using the useAsync hook from the react-async library you can use the watch or the watchFn option the watch for changes. So changing the following line:

    const {data, error, isLoading} = useAsync({ promiseFn: loadData, id: parseInt(id)});
    

    to:

    const {data, error, isLoading} = useAsync({ promiseFn: loadData, id: parseInt(id), watch: id});
    

    did the trick.