Search code examples
javascriptreactjsaxiosnext.jsfetch

Next js Button reload site and new fetch


I want to create a refresh Button. Reloading the page already works, but unfortunately the data is not re-fetched. Does anyone of you have an idea?

The code from the update button is:

    const { reload, query } = useRouter();

                    <Button
                        onClick={() => {
                            reload();
                        }}
                    >
                        Refresh
                    </Button>

The code from the fetch is:

const { data } = await axios.get(`http://localhost:5000//${nr}`);
        const extractedData = data.data;
        setData(extractedData);

        if (extractedData) {
            const unixTimestamp = data.data.unixtime;
            const millisecons = unixTimestamp * 1000;
            const dateObj = new Date(millisecons);
            const humanDateformat = dateObj.toLocaleString();
            setunixTime(humanDateformat);
        }
    }, []);

Solution

  • It appears that you might want to recall the query and not refresh the page. You can assign the fetch call to a function and call the function on click. This would look something like the following:

    import { useEffect, useState } from 'react';
    
    const Page = () => {
      const nr = '/api/route/path';
      const [data, setData] = useState([]);
    
      const fetchData = async () => {
        try {
          const { data } = await axios.get(`http://localhost:5000//${nr}`);
          setData(data.data);
          console.log(data.data);
        } catch(e) {
         console.log(e);
        }
      }
      
      useEffect(() => { fetchData() }, []); //fetch data on page load
     
      return <Button disabled={loading} onClick={fetchData}>Refresh</Button>;
    }