ApolloClient v3 fetchMore with nested query results - reactjs

I'm using ApolloClient 3 the GitHub GraphQL API to retrieve all releases from a repo.
This is what the query looks like:
query ($owner: String!, $name: String!, $first: Int, $after: String, $before: String) {
repository(owner: $owner, name: $name) {
id
releases(orderBy: {field: CREATED_AT, direction: DESC}, first: $first, after: $after, before: $before) {
nodes {
name
publishedAt
resourcePath
tagName
url
id
isPrerelease
description
descriptionHTML
}
totalCount
pageInfo {
endCursor
hasNextPage
hasPreviousPage
startCursor
}
}
}
}
This is what the result payload looks like:
This returns me the first x entries (nodes). So far, all good.
I need to implement pagination and I make use of the fetchMore function provided by ApolloClient useQuery. Calling fetchMore fetches the next x entries successfully but these are not displayed in my component list.
According to the ApolloClient Pagination documentation, it seems necessary to handle the merging of the fetchMore results with the ApolloClient caching mechanism. The documentation is understandable for simple situations but I am struggling to implement a solution for the situation where the actual array of results that needs to be merged togeher is deeply nested in the query result (repository -> releases -> nodes).
This is my implementation of the InMemoryCache options merge:
const inMemoryCacheOptions = {
addTypename: true,
typePolicies: {
ReleaseConnection: {
fields: {
nodes: {
merge(existing, incoming, options) {
const previous = existing || []
const results = [...previous, ...incoming]
return results
}
}
}
},
}
}
The results array here contains the full list, including the existing entries and the new x entries. This is essentially the correct result. However, my component list which is using the useQuery and fetchMore functionality does not get the new entries after the fetchMore is called.
I have tried various combinations in the inMemoryCacheOptions code above but so far I have been unsuccessful.
To add more context, this is the related component code:
export default function Releases() {
const { loading, error, data, fetchMore } = useQuery(releasesQuery, {
variables: {
owner: "theowner",
name: "myrepo",
first: 15
}
});
if (loading) return null;
if (error) {
console.error(error);
return null;
}
if (data) {
console.log(data?.repository?.releases?.pageInfo?.endCursor);
}
const handleFetchMore = () => {
fetchMore({
variables: {
first: 15,
after: data?.repository?.releases?.pageInfo?.endCursor
}
});
};
return (
<div>
<ul>
{data?.repository?.releases?.nodes?.map(release => (
<li key={release.id}>{release.name}</li>
))}
</ul>
<button onClick={handleFetchMore}>Fetch More</button>
</div>
);
}
After fetchMore the component doesn't rerender with the new data.
If anyone has any other ideas that I could try, I'd be grateful.

I finally managed to solve this. There was no change to the react component code but the InMemoryCacheOptions now looks like this:
const inMemoryCacheOptions = {
addTypename: true,
typePolicies: {
Repository: {
fields: {
releases: {
keyArgs: false,
merge(existing, incoming) {
if (!incoming) return existing;
if (!existing) return incoming;
const { nodes, ...rest } = incoming;
// We only need to merge the nodes array.
// The rest of the fields (pagination) should always be overwritten by incoming
let result = rest;
result.nodes = [...existing.nodes, ...nodes];
return result;
}
}
}
}
}
};
The main change from my original code is that I now define the typePolicy for the releases field of the Repository type. Previously I was trying to get directly to the nodes field of the Release type. Since my Repository type the root of the gql query and used in the component, it now reads the merged results from the cache.
If I specified the typePolicy for Query as mentioned in the docs, I would not be able to specify the merge behaviour for the releases field because it would be one level too deep (i.e. Query -> repository -> releases). This is what lead to my confusion in the beginning.

Related

InMemoryCache from #apollo/client gives warning

I have started getting this warning, when I update an "Transaction" with a mutation.
The code is old and have newer showed this warning before. I do not know when this regression started.
Oddly enough, In my mind there should be no cache either, since fetchPolicy: "network-only" is set.
How can I get rid of the warning?
invariant.esm.js:42 Cache data may be lost when replacing the transactions field of a Query object.
To address this problem (which is not a bug in Apollo Client),
define a custom merge function for the Query.transactions field,
so InMemoryCache can safely merge these objects:
existing: [{"__ref":"Transaction:5feabda25e7967001267ffd2"},
{"__ref":"Transaction:5feabda55e7967001267ffd3"},
{"__ref":"Transaction:5feabda75e7967001267ffd4"},
{"__ref":"Transaction:5feabda95e7967001267ffd5"},
{"__ref":"Transaction:5feabdab5e7967001267ffd6"},
{"__ref":"Transaction:60127209c3731400116fe0c5"},
{"__ref":"Transaction:602543cde12cd00011881a8b"},
{"__ref":"Transaction:602544e7e12cd00011881a91"},
{"__ref":"Transaction:602f7d9be14be20011a5cbec"},
{"__ref":"Transaction:6033b4d5ad34870011e7ba08"},
{"__ref":"Transaction:603494fbad34870011e7bf07"},
{"__ref":"Transaction:6038a0519d844c00116e544f"},
{"__ref":"Transaction:6038a05f9d844c00116e545e"},
{"__ref":"Transaction:6038a06c9d844c00116e549e"},
{"__ref":"Transaction:6038a06f9d844c00116e54a1"},
{"__ref":"Transaction:6038a0549d844c00116e5452"},
{"__ref":"Transaction:6038a0629d844c00116e545f"},
{"__ref":"Transaction:6038a0699d844c00116e549a"},
{"__ref":"Transaction:603cd5c39d844c00116f232b"},
{"__ref":"Transaction:603ce07d9d844c00116f2342"},
{"__ref":"Transacti
incoming: [{"__ref":"Transaction:5feabda25e7967001267ffd2"},
{"__ref":"Transaction:5feabda55e7967001267ffd3"},
{"__ref":"Transaction:5feabda75e7967001267ffd4"},
{"__ref":"Transaction:5feabda95e7967001267ffd5"},
{"__ref":"Transaction:5feabdab5e7967001267ffd6"},
{"__ref":"Transaction:60127209c3731400116fe0c5"},
{"__ref":"Transaction:602543cde12cd00011881a8b"},
{"__ref":"Transaction:602544e7e12cd00011881a91"},
{"__ref":"Transaction:602f7d9be14be20011a5cbec"},
{"__ref":"Transaction:6033b4d5ad34870011e7ba08"},
{"__ref":"Transaction:603494fbad34870011e7bf07"},
{"__ref":"Transaction:6038a0519d844c00116e544f"},
{"__ref":"Transaction:6038a05f9d844c00116e545e"},
{"__ref":"Transaction:6038a06c9d844c00116e549e"},
{"__ref":"Transaction:6038a06f9d844c00116e54a1"},
{"__ref":"Transaction:6038a0549d844c00116e5452"},
{"__ref":"Transaction:6038a0629d844c00116e545f"},
{"__ref":"Transaction:6038a0699d844c00116e549a"},
{"__ref":"Transaction:603cd5c39d844c00116f232b"},
{"__ref":"Transaction:603ce07d9d844c00116f2342"},
{"__ref":"Transacti
For more information about these options, please refer to the documentation:
* Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers
* Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects
From code that looks like this:
const UPDATE_TRANSACTION = gql`
mutation updateTransaction($input: UpdateTransactionInput!) {
updateTransaction(input: $input) {
_id
status
}
}
`;
export const DealBlotterGrid = ({ startDate }: DealBlotterGridPropsType): ReactElement => {
const swedenIsoString = moment.tz(startDate, "Europe/Stockholm").format();
const { loading, error, data } = useQuery(GET_TRANSACTIONS, {
variables: { tradeTimestampStart: swedenIsoString },
fetchPolicy: "network-only",
pollInterval: 10000
});
const [updateTransactionStatus] = useMutation(UPDATE_TRANSACTION, {
refetchQueries: [
{
query: GET_TRANSACTIONS,
variables: { tradeTimestampStart: swedenIsoString }
}
]
});
...

How to use detalization queries in apollo graphql reactjs?

Suppose data - is data from a parent query.
Child react-component:
const ShowDetails = ({data}) => {
const { loading, error, data_details } = useQuery(someQueryAsksAdditionalFileldsForEntryAlreadyPresentInCache);
}
someQueryAsksAdditionalFileldsForEntryAlreadyPresentInCache -- asks for additional fields that are missing in data.
When (!loading && !error) data_details will have requested fields.
Issue: data_details will have only requested fields.
Question: Is there a way to use parent data with merged-additional-requested fields in ShowDetails and ignore data_details?
In Chrome with help of Apollo devtools I see that apollo-cache has one entry from merged data and data_details.
I do not want to re-fetch all existed entries in data.
Example:
Parent component query:
const bookQuery = gql`
query ($bookId: ID!) {
book(id: $bookId) {
id
author
}
}
`
Details query:
const bookEditionsQuery = gql`
query ($bookId: ID!) {
book(id: $bookId) {
id
editions {
publisher
year
}
}
}
`
const bookReviewQuery = gql`
query ($bookId: ID!) {
book(id: $bookId) {
id
review {
user
score
date
}
}
}
`
All this queries will populate the same bucket in Apollo cache: book with id.
What is necessary to achieve: in react component BookDetails:
have 1 object with:
data.author
data.editions[0].year
data.review[0].user
Logically - this is one entry in cache.
Thank you for your help.
Almost nothing to save by using already fetched [and passed from parent] data ... only author ... all review and edition must be fetched, no cache usage at all.
... fetching review and editions by book resolver helps apollo cache to keep relation but also requires API to use additional ('book') resolver [level] while it is not required ... review and editions resolvers should be callable directly with book id ... and f.e. can be used by separate <Review /> sub component ... or review and editions called within one request using the same id parameter.
Just use data and dataDetails separately in component - avoid code complications, keep it simply readable:
const ShowDetails = ({data}) => {
const { loading, error, data:dataDetails } = useQuery(someQueryAsksAdditionalFileldsForEntryAlreadyPresentInCache);
}
if(loading) return "loading...";
return (
<div>
<div>author: {data.author}</div>
{dataDetails.review.map(...
... if you really want to join data
const ShowDetails = ({data}) => {
const [bookData, setBookData] = useState(null);
const { loading, error, data:dataDetails } = useQuery(someQueryAsksAdditionalFileldsForEntryAlreadyPresentInCache, {
onCompleted: (newData) => {
setBookData( {...data, ...newData } );
}
});
if(bookData) return ...
// {bookData.author}
// bookData.review.map(...

GatsbyJS getting data from Restful API

I am new in both React and GatsbyJS. I am confused and could not make figuring out in a simple way to load data from third-party Restful API.
For example, I would like to fetch data from randomuser.me/API and then be able to use the data in pages.
Let’s say something like this :
import React from 'react'
import Link from 'gatsby-link'
class User extends React.Component {
constructor(){
super();
this.state = {
pictures:[],
};
}
componentDidMount(){
fetch('https://randomuser.me/api/?results=500')
.then(results=>{
return results.json();
})
.then(data=>{
let pictures = data.results.map((pic,i)=>{
return(
<div key={i} >
<img key={i} src={pic.picture.medium}/>
</div>
)
})
this.setState({pictures:pictures})
})
}
render() {
return (<div>{this.state.pictures}</div>)
}
}
export default User;
But I would like to get the help of GraphQL in order to filter & sort users and etc…..
Could you please help me to find the sample to how I can fetch data and insert them into GraphQL on gatsby-node.js?
If you want to use GraphQL to fetch your data, you have to create a sourceNode. The doc about creating a source plugin could help you.
Follow these steps to be able to query randomuser data with GraphQL in your Gatsby project.
1) Create nodes in gatsby-node.js
In your root project folder, add this code to gatsby-node.js:
const axios = require('axios');
const crypto = require('crypto');
exports.sourceNodes = async ({ actions }) => {
const { createNode } = actions;
// fetch raw data from the randomuser api
const fetchRandomUser = () => axios.get(`https://randomuser.me/api/?results=500`);
// await for results
const res = await fetchRandomUser();
// map into these results and create nodes
res.data.results.map((user, i) => {
// Create your node object
const userNode = {
// Required fields
id: `${i}`,
parent: `__SOURCE__`,
internal: {
type: `RandomUser`, // name of the graphQL query --> allRandomUser {}
// contentDigest will be added just after
// but it is required
},
children: [],
// Other fields that you want to query with graphQl
gender: user.gender,
name: {
title: user.name.title,
first: user.name.first,
last: user.name.last,
},
picture: {
large: user.picture.large,
medium: user.picture.medium,
thumbnail: user.picture.thumbnail,
}
// etc...
}
// Get content digest of node. (Required field)
const contentDigest = crypto
.createHash(`md5`)
.update(JSON.stringify(userNode))
.digest(`hex`);
// add it to userNode
userNode.internal.contentDigest = contentDigest;
// Create node with the gatsby createNode() API
createNode(userNode);
});
return;
}
I used axios to fetch data so you will need to install it: npm install --save axios
Explanation:
The goal is to create each node for each piece of data you want to use.
According to the createNode documentation, you have to provide an object with few required fields (id, parent, internal, children).
Once you get the results data from the randomuser API, you just need to create this node object and pass it to the createNode() function.
Here we map to the results as you wanted to get 500 random users https://randomuser.me/api/?results=500.
Create the userNode object with the required and wanted fields.
You can add more fields depending on what data you will want to use in your app.
Just create the node with the createNode() function of the Gatsby API.
2) Query your data with GraphQL
Once you did that, run gatsby develop and go to http://localhost:8000/___graphql.
You can play with GraphQL to create your perfect query. As we named the internal.type of our node object 'RandomUser', we can query allRandomUser to get our data.
{
allRandomUser {
edges {
node {
gender
name {
title
first
last
}
picture {
large
medium
thumbnail
}
}
}
}
}
3) Use this query in your Gatsby page
In your page, for instance src/pages/index.js, use the query and display your data:
import React from 'react'
import Link from 'gatsby-link'
const IndexPage = (props) => {
const users = props.data.allRandomUser.edges;
return (
<div>
{users.map((user, i) => {
const userData = user.node;
return (
<div key={i}>
<p>Name: {userData.name.first}</p>
<img src={userData.picture.medium} />
</div>
)
})}
</div>
);
};
export default IndexPage
export const query = graphql`
query RandomUserQuery {
allRandomUser {
edges {
node {
gender
name {
title
first
last
}
picture {
large
medium
thumbnail
}
}
}
}
}
`;
That is it!
Many thanks, this is working fine for me, I only change small parts of the gastbyjs-node.js because it makes an error when use sync & await, I think I need change some section of a build process to use babel to allow me to use sync or await.
Here is the code which works for me.
const axios = require('axios');
const crypto = require('crypto');
// exports.sourceNodes = async ({ boundActionCreators }) => {
exports.sourceNodes = ({boundActionCreators}) => {
const {createNode} = boundActionCreators;
return new Promise((resolve, reject) => {
// fetch raw data from the randomuser api
// const fetchRandomUser = () => axios.get(`https://randomuser.me/api/?results=500`);
// await for results
// const res = await fetchRandomUser();
axios.get(`https://randomuser.me/api/?results=500`).then(res => {
// map into these results and create nodes
res.data.results.map((user, i) => {
// Create your node object
const userNode = {
// Required fields
id: `${i}`,
parent: `__SOURCE__`,
internal: {
type: `RandomUser`, // name of the graphQL query --> allRandomUser {}
// contentDigest will be added just after
// but it is required
},
children: [],
// Other fields that you want to query with graphQl
gender: user.gender,
name: {
title: user.name.title,
first: user.name.first,
last: user.name.last
},
picture: {
large: user.picture.large,
medium: user.picture.medium,
thumbnail: user.picture.thumbnail
}
// etc...
}
// Get content digest of node. (Required field)
const contentDigest = crypto.createHash(`md5`).update(JSON.stringify(userNode)).digest(`hex`);
// add it to userNode
userNode.internal.contentDigest = contentDigest;
// Create node with the gatsby createNode() API
createNode(userNode);
});
resolve();
});
});
}
The accepted answer for this works great, just to note that there's a deprecation warning if you use boundActionCreators. This has to be renamed to actions to avoid this warning.
You can get data at the frontend from APIs using react useEffect. It works perfectly and you will no longer see any error at builtime
const [starsCount, setStarsCount] = useState(0)
useEffect(() => {
// get data from GitHub api
fetch(`https://api.github.com/repos/gatsbyjs/gatsby`)
.then(response => response.json()) // parse JSON from request
.then(resultData => {
setStarsCount(resultData.stargazers_count)
}) // set data for the number of stars
}, [])
The answers given above work, except the query in step 2 seems to only return one node for me. I can return all nodes by adding totalCount as a sibling of edges. I.e.
{
allRandomUser {
totalCount
edges {
node {
id
gender
name {
first
last
}
}
}
}
}

readQuery not working with pagination in Apollo & GraphQL app

I've got the following setup for my app. I have a LinkList component that renders a list of Link components. Then I also have a CreateLink component to create new links. Both are rendered under different routes with react-router:
<Switch>
<Route exact path='/create' component={CreateLink}/>
<Route exact path='/:page' component={LinkList}/>
</Switch>
The Link type in my GraphQL schema looks as follows:
type Link implements Node {
url: String!
postedBy: User! #relation(name: "UsersLinks")
votes: [Vote!]! #relation(name: "VotesOnLink")
comments: [Comment!]! #relation(name: "CommentsOnLink")
}
I'm using Apollo Client and want to use the imperative store API to update the list after new Link was created in the CreateLink component.
await this.props.createLinkMutation({
variables: {
description,
url,
postedById
},
update: (store, { data: { createLink } }) => {
const data = store.readQuery({ query: ALL_LINKS_QUERY }) // ERROR
console.log(`data: `, data)
}
})
The problem is that store.readQuery(...) throws an error:
proxyConsole.js:56 Error: Can't find field allLinks({}) on object (ROOT_QUERY) {
"allLinks({\"first\":2,\"skip\":10})": [
{
"type": "id",
"id": "Link:cj3ucdguyvzdq0131pzvn37as",
"generated": false
}
],
"_allLinksMeta": {
"type": "id",
"id": "$ROOT_QUERY._allLinksMeta",
"generated": true
}
}.
Here is how I am fetching the list of links in my LinkList component:
export const ALL_LINKS_QUERY = gql`
query AllLinksQuery($first: Int, $skip: Int) {
allLinks(first: $first, skip: $skip) {
id
url
description
createdAt
postedBy {
id
name
}
votes {
id
}
}
_allLinksMeta {
count
}
}
`
export default graphql(ALL_LINKS_QUERY, {
name: 'allLinksQuery',
options: (ownProps) => {
const { pathname } = ownProps.location
const page = parseInt(pathname.substring(1, pathname.length))
return {
variables: {
skip: (page - 1) * LINKS_PER_PAGE,
first: LINKS_PER_PAGE
},
fetchPolicy: 'network-only'
}
}
}) (LinkList)
I am guessing that the issue somehow has to do with my pagination approach, but I still don't know how to fix it. Can someone point me into the right direction here?
How to read a paginated list from the store depends on how you do the pagination. If you're using fetchMore, then all the data will be stored under the original keys of the query, which in this case I guess was fetched with { first: 2, skip: 0 }. That means in order to read the updated list from the store, you would have to use the same parameters, using { first: 2, skip: 0 } as variables.
PS: The reason Apollo does it this way is because it still allows you to relatively easily update a list via a mutation or update store. If each page was stored separately, it would be very complicated to insert an item in the middle or the beginning of the list, because all of the pages would potentially have to be shifted.
That said, we might introduce a new client-side directive called #connection(name: "ABC") which would let you explicitly specify under which key the connection is to be stored, instead of automatically storing it under the original variables. Happy to talk more about it if you want to open an issue on Apollo Client.

React Apollo first object from subscription not being merge into previous data it actually gets removed

I have a query which gets me a list of notes and a subscription which listens and inserts new notes by altering the query. However the problem is the first note doesn't get added.
So let me add more detail, initially the query response with an object which contains an attribute called notes which is an array of 0 length, if we try and add a note the attribute gets removed. The note is created so if I refresh my application the query will return the note then If I try and add a note again the note gets added to the array in the query object.
Here is my notes container where I query for notes and create a new property to subscribe to more notes.
export const NotesDataContainer = component => graphql(NotesQuery,{
name: 'notes',
props: props => {
console.log(props); // props.notes.notes is undefined on first note added when none exists.
return {
...props,
subscribeToNewNotes: () => {
return props.notes.subscribeToMore({
document: NotesAddedSubscription,
updateQuery: (prevRes, { subscriptionData }) => {
if (!subscriptionData.data.noteAdded) return prevRes;
return update(prevRes, {
notes: { $unshift: [subscriptionData.data.noteAdded] }
});
},
})
}
}
}
})(component);
Any help would be great, thanks.
EDIT:
export const NotesQuery = gql`
query NotesQuery {
notes {
_id
title
desc
shared
favourited
}
}
`;
export const NotesAddedSubscription = gql`
subscription onNoteAdded {
noteAdded {
_id
title
desc
}
}
`;
Another EDIT
class NotesPageUI extends Component {
constructor(props) {
super(props);
this.newNotesSubscription = null;
}
componentWillMount() {
if (!this.newNotesSubscription) {
this.newNotesSubscription = this.props.subscribeToNewNotes();
}
}
render() {
return (
<div>
<NoteCreation onEnterRequest={this.props.createNote} />
<NotesList
notes={ this.props.notes.notes }
deleteNoteRequest={ id => this.props.deleteNote(id) }
favouriteNoteRequest={ this.props.favouriteNote }
/>
</div>
)
}
}
Another edit:
https://github.com/jakelacey2012/react-apollo-subscription-problem
YAY got it to work, simply the new data sent down the wire needs to be the same shape as the original query.
e.g.
NotesQuery had this shape...
query NotesQuery {
notes {
_id
title
desc
shared
favourited
}
}
yet the data coming down the wire on the subscription had this shape.
subscription onNoteAdded {
noteAdded {
_id
title
desc
}
}
notice shared & favourited are missing from the query on the subscription. If we added them it would now work.
This is the problem, react-apollo internally detects a difference and then doesn't add the data I guess It would be useful if there was a little more feed back.
I'm going to try and work with the react-apollo guys to see if we can put something like that in place.
https://github.com/apollographql/react-apollo/issues/649

Resources