最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React-query - refetch data when component mounts - Stack Overflow

programmeradmin1浏览0评论

Is there a way to refetch the data when the ponent mounts? At the moment with react-router if I navigate around my app it fetches the data once and then if I navigate away and e back the data is still the old one and not a new request?

I have not wrapped my fetch call in useEffect.

const fetchInfo = async () => {
        const res = await fetch(`/api/${id}`);
        return res.json();
    };

    const { data, status } = useQuery('tableInfo', fetchInfo, {
        staleTime: 5000,
    });

using as:

{status === 'error' && (
                <div className="mt-5">Error fetching data!</div>
            )}
            {status === 'loading' && (
                <div className="mt-5">Loading data ...
                   
                </div>
            )}
            {status === 'success' && (
                <div className="mt-5">
                    <p>Result will be here</p>
                </div>
            )}

Is there a way to refetch the data when the ponent mounts? At the moment with react-router if I navigate around my app it fetches the data once and then if I navigate away and e back the data is still the old one and not a new request?

I have not wrapped my fetch call in useEffect.

const fetchInfo = async () => {
        const res = await fetch(`/api/${id}`);
        return res.json();
    };

    const { data, status } = useQuery('tableInfo', fetchInfo, {
        staleTime: 5000,
    });

using as:

{status === 'error' && (
                <div className="mt-5">Error fetching data!</div>
            )}
            {status === 'loading' && (
                <div className="mt-5">Loading data ...
                   
                </div>
            )}
            {status === 'success' && (
                <div className="mt-5">
                    <p>Result will be here</p>
                </div>
            )}
Share Improve this question asked Oct 21, 2021 at 12:35 SoleSole 3,35818 gold badges71 silver badges134 bronze badges 1
  • Similar question is answered stackoverflow./questions/62587993/… – Ram Rana Commented Oct 21, 2021 at 12:52
Add a ment  | 

1 Answer 1

Reset to default 3

With your setup, if you fetch your data, move to another view and e back (at least 5 seconds later) it will refetch - if you navigate and e back BEFORE those 5 seconds - it should not.

If you want to prevent re-fetching when you consider data not being stale over time (or not so quickly anyway), set staleTime to more than just 5 seconds (up to Infinity)

If you want to re-fetch data on every navigation to that view - don't set staleTime at all

发布评论

评论列表(0)

  1. 暂无评论