Do you mean not start the fetching until you click a button? If that's your use case you can pass null as the key of useSWR and then change it to the URL.
function FetchOnClick() {
const [shouldFetch, setShouldFetch] = React.useState(false);
const { data } = useSWR(shouldFetch ? null : "/api/users/1", fetcher);
function handleClick() {
setShouldFetch(true);
}
return (
<>
<button disable={shouldFetch} onClick={handleClick}>Fetch</button>
{data ? <h1>{data.fullName}</h1> : null}
</>
);
}
Something like that, another option is to move the data fetching and the UI rendered with that data to a second component and use the handleClick to control if you should render it or not.
function RenderOnClick() {
const [shouldRender, setShouldRender] = React.useState(false);
function handleClick() {
setShouldRender(true);
}
return (
<>
<button disable={shouldFetch} onClick={handleClick}>Fetch</button>
{shouldRender && <FetchAndRender />}
</>
);
}
function FetchAndRender() {
const { data } = useSWR("/api/users/1", fetcher);
return (
<>
{data ? <h1>{data.fullName}</h1> : null
</>
);
}
Both ways will only start fetching after you click the button, I would personally go with the second way.
Thanks a lot
I would also go with the first example, It doesn't force you to split code into different chunks when not needed. The first example also allows for a better separation of logic and view data which is always good!
Most helpful comment
Do you mean not start the fetching until you click a button? If that's your use case you can pass
nullas the key ofuseSWRand then change it to the URL.Something like that, another option is to move the data fetching and the UI rendered with that data to a second component and use the handleClick to control if you should render it or not.
Both ways will only start fetching after you click the button, I would personally go with the second way.