I have an API with SWR that returns data something like this:
const {data: data, error: error} = useSWR('fetchData', fetcher, { refreshInterval: 5000 })
I want to display the status of my data data.status which is easy:
<p>{data.status}</P>
<button onClick={changeStatus}>change status</button>
but there are sometimes that I need to manually change what needs to be displayed, for that I tried to store data.status to a variable first and then change it using two things:
if (data){
status = data.status
}
const changeStatus = () => {
status = 'bad'
}
which simply doesn't change status AND
const [status, setStatus] = useState('');
if (data){
setStatus(data.status)
}
const changeStatus = () => {
setStatus('bad')
}
which gives me "too many iterations" error!
So how can I manually change the data I get from SWR in a way that it still calls the api every 5 seconds and update the data accordingly?
you cannot set it like that. you need to use useEffect if you want to store status in a state
useEffect(() => {
if (data) {
setStatus(data.status);
}
}, [data])