'GraphQL on component load, Query will sometimes return populated properties as null

I am using graphQl with react with apollo client and mongoose. Sometimes when I click on a component. rand om data will return from this useQuery as null.

    // must define novel as a state to use useEffect correctly
    const [novel, setNovel] = useState({});

    const { loading, data } = useQuery(GET_NOVEL, {
        variables: { _id: novelId }
    });

    // use effect ensures that all novel data is completely loaded
    // before rendering the SingleNovel page
    useEffect(() => {
        console.log(data?.novel);
        // if there's data to be stored
        if (data) {
            setNovel(data.novel) 
            
        }
    }, [data, loading, novel]);

        export const GET_NOVEL = gql`
    query getNovel($_id: ID!) {
        novel(_id: $_id) {
          _id
          title
          description
          penName
          user {
            _id
            username
            email
          }
          favorites{
            _id
          }
          createdAt
          reviews {
            _id
            reviewText
            rating
            createdAt
            user{
                _id
                username
            }
          }
          chapterCount
          reviewCount
        }
    }
`

Specifically, the novel.user.username and reviews.rating property come back as null. On reload of the page however, the data seems to populate the fields normally.

How can I fix this?

Heres the resolver

novel: async (parent, { _id }) => {
            // returns single novel from the novel id given
            const novel = await Novel.findOne({ _id })
            .populate('user')
            // populate the reviews for the novel but also populate
            // the info within the reviews of the user who made each review.
            .populate({
                path: 'reviews',
                populate: {path: 'user'}
            })
            .exec();

            console.log(novel)
            return novel;
        },


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source