I pull data with react-query and need to store it in state due to some form editing that is happening later.
Before the form editing, it worked well:
import { useQuery } from '@apollo/client';
import { SINGLE_PARTICIPANT_QUERY } from 'queries/participantQueries';
import { ProfileGeneral } from './ProfileGeneral';
const ProfilePage = ({ id }) => {
const {data, loading, error} = useQuery(SINGLE_PARTICIPANT_QUERY, {
variables: {
id
}
});
if (loading) {
return <div>Loading</div>;
}
if (error) {
return (
<div>
{error.message} />
</div>
);
}
const { participant } =data;
return (
<div>
<ProfileGeneral participant={participant} />
</div>
But after trying to add it into state, I keep getting an error message, indicating that it renders without having the data ready.
import { useQuery } from '@apollo/client';
import { SINGLE_PARTICIPANT_QUERY } from 'queries/participantQueries';
import { ProfileGeneral } from './ProfileGeneral';
import { useEffect, useState } from 'react';
const ProfilePage = ({ id }) => {
const [participant, setParticipant] = useState(null);
const { data, loading, error } = useQuery(SINGLE_PARTICIPANT_QUERY, {
variables: {
id
}
});
useEffect(() => {
if (data && data.participant) {
setParticipant(data.participant);
}
}, [data, participant]);
if (loading) {
return <div>Loading</div>;
}
if (error) {
return (
<div>
{error.message} />
</div>
);
}
return (
<div>
<ProfileGeneral participant={participant} />
</div>
I get back:
Server Error
TypeError: Cannot read properties of null (reading 'firstName')
This error happened while generating the page. Any console logs will be displayed in the terminal window.
I know that I need to make it wait or re-render as soon as it has the data from the query, but I am not sure how to prevent it.
Thank you for taking a look!