You definitely cannot / should not call a setter function of useState
during render, as this violates a core principle of React that render functions should be pure. What you can do is:
const { data: existingSchedules } = useExistingScheduleDates(...)
useEffect(() => {
setDates(...)
}, [existingSchedules])
- set it in the
onSuccess
callback of useQuery
const { data: existingSchedules } = useQuery(
'key',
queryFn,
{
onSuccess: data => setDates(...)
}
)
Both of these should work, but the question remains: Why would you need to do that? react-query is a state manager per se, so there is really no need to store that additionally in client state. The best way to use react-query is to keep the client state and the server state separated. I would suggest to store the user selection (selectedDates
) in useState
, have the server data handled completely by react-query (existingSchedules
), and combine them in the render function if you need to:
const { data: existingSchedules } = useExistingScheduleDates(...)
const [selectedDates, setSelectedDates] = React.useState<selectedDates>({})
const someComputedThing = computeSomeThing(existingSchedules, selectedDates)
sorry for the bad naming, I have no idea how existingSchedules
works together with selectedDates
, but I hope you get the idea :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…