Apollo client fragments not embedding data
Asked Answered
B

1

15

This is the first time I've ventured into fragments and I can't see where I'm screwing up, but it definitely isn't working! In GraphiQL it's working fine:

query Tasks($taskIds: [String]!) {
    tasks(taskIds: $taskIds) {
        ...taskDisplay
    }
}
fragment taskDisplay on Task {
    _id
    name
    description
    status
    children {
        _id
    }
}

Here's what's in my client app:

import { gql } from "@apollo/client";

export const TASK_FRAGMENT = gql`
    fragment taskDisplay on Task {
        _id
        name
        description
        status
        children {
            _id
        }
    }
`;

export const TASKS = gql`
    query Tasks($taskIds: [String]!) {
        tasks(taskIds: $taskIds) {
            ...taskDisplay
        }
    }
    ${TASK_FRAGMENT}
`;

So, the server returns the data correct as I can see in the Network tab of Chrome, but the data received by the useQuery result is an empty object. What gives?

Using @apollo/[email protected] (I have downgraded to 3.1.0 with same results)

EDIT:

Adding more info. My code is about as simple as it could be using a hook. Here's what's happening:

import { useQuery, gql } from "@apollo/client";
import { TASK_FRAGMENT } from "../pages/task/queries";

const ROOT_TASK_QUERY = gql`
    query Project($projectId: String!) {
        rootTask(projectId: $projectId) {
            ...taskDisplay
        }
    }
    ${TASK_FRAGMENT}
`;

const useProject = ({ variables }) => {
    return useQuery(ROOT_TASK_QUERY, {
        variables,
    });
};
export default useProject;

And this is just logging the query itself:

Missing Data

Bahadur answered 11/8, 2020 at 16:29 Comment(5)
your returned data is missing the __typename field, might this be the cause?Saucier
OMG that's awesome. I had turned that off when I was learning Apollo 'cause I didn't see it's utility for what I was doing. That's exactly what it was. const cache = new InMemoryCache({ addTypename: false });Bahadur
Post it as an answer and I'll mark it!Bahadur
My pleasure, will doSaucier
Why does __typename need to be present for fragments to be embedded?Celestine
S
17

Your returned data is missing the __typename field

Saucier answered 11/8, 2020 at 17:46 Comment(6)
1.5 years later, you fixed my issue too! Much appreciatedSuellensuelo
Also 1.5 years later, and you solved my issue! Thanks!Bashibazouk
It can also be that you've set addTypename in the Apollo options to false.Paperboard
Can anybody explain why this is the case?Celestine
3 years later for me!Bifoliate
4 years here to meSeventeenth

© 2022 - 2024 — McMap. All rights reserved.