admin管理员组

文章数量:1401673

How can I parse a stored JSON response in React and pass to a component that is expecting graphQL response?

Is there a way to add the __typenames from the query RatingQuery?

This is what I am trying, but it is not reading the data correctly:

const client = new ApolloClient({
  cache: new InMemoryCache({ addTypename: true })
});

client.cache.writeQuery({
  query: __Query,
  data: ratingDataWithoutTypename,
});
const ratingSummaryData = client.cache.readQuery<RatingQuery>({ query: __Query });
console.log('ratingSummaryData:', ratingSummaryData);

This is how ratingDataWithoutTypename looks:

const ratingDataWithoutTypename = {
  "productRatingSummary": {
    "sectionHeadingAccessibilityText": "Reviews",
    "summary": {
      "primary": "9.0",
      "secondary": "Wonderful",
      "theme": "positive"
    },
    "info": null,
  }
}

though only root elements are getting read, and the objects are empty - summary:

{
  "productRatingSummary": {
    "sectionHeadingAccessibilityText": "Reviews",
    "summary": {},
    "info": null
  }
}

If I add __typename to each object, this works well. So need to find a way to do that. The JSON is coming from a REST API.

How can I parse a stored JSON response in React and pass to a component that is expecting graphQL response?

Is there a way to add the __typenames from the query RatingQuery?

This is what I am trying, but it is not reading the data correctly:

const client = new ApolloClient({
  cache: new InMemoryCache({ addTypename: true })
});

client.cache.writeQuery({
  query: __Query,
  data: ratingDataWithoutTypename,
});
const ratingSummaryData = client.cache.readQuery<RatingQuery>({ query: __Query });
console.log('ratingSummaryData:', ratingSummaryData);

This is how ratingDataWithoutTypename looks:

const ratingDataWithoutTypename = {
  "productRatingSummary": {
    "sectionHeadingAccessibilityText": "Reviews",
    "summary": {
      "primary": "9.0",
      "secondary": "Wonderful",
      "theme": "positive"
    },
    "info": null,
  }
}

though only root elements are getting read, and the objects are empty - summary:

{
  "productRatingSummary": {
    "sectionHeadingAccessibilityText": "Reviews",
    "summary": {},
    "info": null
  }
}

If I add __typename to each object, this works well. So need to find a way to do that. The JSON is coming from a REST API.

Share Improve this question asked Mar 22 at 12:56 Amit MAmit M 111 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

Got answer here: https://github/apollographql/apollo-client/issues/12472?reload=1

The cache would only accept that like you do it in the first post if you already had the __typename in. The cache doesn't know about your schema, so it can't make up __typename properties that don't already come from the server.

本文标签: reactjsParse JSON response to apolloclient queryStack Overflow