How to rerender function component when id changed in url

2.3k Views Asked by At

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>
      </>
     );
}
2

There are 2 best solutions below

0
On BEST ANSWER

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.

3
On

Async functions should be called inside useEffect hook. The useEffect will always be called when id changes.

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 [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState(null);

  useEffect(() => {
    const { data, error, isLoading } = useAsync({
      promiseFn: loadData,
      id: parseInt(id)
    });
    setIsLoading(isLoading);
    setError(error);
    setData(data)
  }, [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>
      </>
    );
}