简体   繁体   中英

React how to use setInterval with useEfecct and axios request

Where I've to use setInterval to fetch every second? When i try it i get this error Uncaught SyntaxError: Unexpected identifier

  useEffect(() => {
    const getHistory = async () => {
      const res = await axios.get('/api/payment', {
        headers: { Authorization: token },
      });
      setHistory(res.data);
    };
    getHistory();
  }, [token, delivered]);

You can useswr for this and benefit from not only built-in revalidation on interval, but also caching and deduplication.

import useSWR from 'swr'

// You can use axios if you want
const fetcher = (...args) => fetch(...args).then(res => res.json())

const { data, error } = useSWR('/api/payment', fetcher, { refreshInterval: 1000 })

if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>Look at all this data: {data.someProperty}</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM