I'm trying to use SWR to fetch list of users connected to the logged in user id provided by a custom hook.
I can't put useSWR
inside either useCallback
or useEffect
or if (loggedInAdvisor) { ... }
... Can't figure out how to do it.
export const fetchDetailedAdvisorPrognoses = (
body: DetailedAdvisorPrognosesRequest
): Promise<DetailedAdvisorPrognoses[]> | null => {
const accessToken = getFromPersistance(ACCESS_TOKEN)
if (!accessToken) {
return null
}
return fetch('https://x/api/v2/advisors/prognoses', {
method: 'POST',
headers: {
...generateDefaultHeaders(),
'Content-Type': 'application/json',
Authorization: getAuthorizationHeader(accessToken),
},
body: JSON.stringify(body), // body data type must match "Content-Type" header
}).then(res => res.json())
}
function Workload(): ReactElement | null {
const { loggedInAdvisor } = useAuthentication()
// yesterday
const fromDate = moment()
.subtract(1, 'day')
.format('YYYY-MM-DD')
// 14 days ahead
const toDate = moment()
.add(13, 'days')
.format('YYYY-MM-DD')
const { data, error } = useSWR<DetailedAdvisorPrognoses[] | null>('fetchWorkloadData', () =>
'detailed',
fetchDetailedAdvisorPrognoses({
advisorIds: [loggedInAdvisor.id], // <-- I want to pause the query until loggedInAdvisor is defined
fromDate,
toDate,
})
)
// todo: display errors better
if (error) {
return <span>Error: {error.message}</span>
}
if (!data) {
return <LoadingV2 isLoading={!data} />
}
if (data && data.length > 0) {
// advisors prognoses is first element in data array
const [first] = data
const days: WorkloadDay[] = Object.keys(first.daysMap).map(date => ({
date,
value: first.daysMap[date],
}))
return <WorkloadLayout before={first.before} days={days} />
}
return null
}