¿Alguien podría proporcionar un ejemplo de paginación implementada con las políticas de campo de Apollo Client 3.0? He estado siguiendo el ejemplo de los documentos para implementar el desplazamiento infinito, pero en mi consola recibo la siguiente advertencia:
The updateQuery callback for fetchMore is deprecated, and will be removed in the next major version of Apollo Client. Please convert updateQuery functions to field policies with appropriate read and merge functions, or use/adapt a helper function (such as concatPagination, offsetLimitPagination, or relayStylePagination) from @apollo/client/utilities. The field policy system handles pagination more effectively than a hand-written updateQuery function, and you only need to define the policy once, rather than every time you call fetchMore.Soy bastante nuevo en Apollo y realmente no entiendo cómo hacerlo de la manera 3.0. Agradecería algunos ejemplos para entender mejor.
Aquí está mi código actual:
import React from "react"; import { useGetUsersQuery } from "./generated/graphql"; import { Waypoint } from "react-waypoint"; const App = () => { const { data, loading, error, fetchMore } = useGetUsersQuery({ variables: { limit: 20, offset: 0 }, }); if (loading) return <div>Loading...</div>; if (error) return <div>Error</div>; return ( <div className="App"> {data && data.users && ( <div> {data.users.map((user, i) => { return ( <div key={i} style={{ margin: "20px 0" }}> <div>{user.id}</div> <div>{user.name}</div> </div> ); })} <Waypoint onEnter={() => { fetchMore({ variables: { offset: data.users.length }, updateQuery: (prev, { fetchMoreResult }) => { console.log("called"); if (!fetchMoreResult) return prev; return Object.assign({}, prev, { users: [...prev.users, fetchMoreResult.users], }); }, }); }} /> </div> )} </div> ); }; export default App;Elimine completamente la función de devolución de llamada updateQuery:
fetchMore({ variables: { offset: data.users.length } });Y cambie su caché a:
import { offsetLimitPagination } from "@apollo/client/utilities"; const cache = new InMemoryCache({ typePolicies: { Query: { fields: { users: offsetLimitPagination(), }, }, }, });Por lo tanto, su consulta en qraphql debe tener argumentos de compensación y límite.
Otras opciones son: concatPagination y relayStylePagination
Si necesita distinguir diferentes solicitudes para los mismos users de campo, ej. coloque keyArg: offsetLimitPagination(["filters"]) y consulte a sus usuarios con filtros arg. Caché lo almacenará por separado.
Más info en comunicado oficial
Para futuros usuarios. Puede lograr la actualización de caché en Apllo> 3.0.0 de la siguiente manera.
const cache = new InMemoryCache({ typePolicies: { Query: { fields: { users: { keyArgs: ["searchString", "type"], // Concatenate the incoming list items with // the existing list items. merge(existing = [], incoming) { return [...existing, ...incoming]; }, } } } } })searchString y type podrían ser sus otros argumentos además de limit & offset .
De esta manera, no necesita hacer ninguna lógica de actualización dentro de la devolución de llamada updateQuery .