apollographql / ac3-state-management-examples Goto Github PK
View Code? Open in Web Editor NEW✨ Learn Apollo Client 3's state management best practices
✨ Learn Apollo Client 3's state management best practices
I get this nasty warning that says my updateQuery will be deprecated in the next major version, but I've not found a working example of cursor based pagination anywhere on the apollo site. I was hoping to find it in this repo :(.
Hi Khalil,
Are you proceeding with the documentation/ blog post regarding persisting the local and remote state in localStorage? Apollo-cache-persist isn't maintained and is not being updated to AC3.
I feel like this is the only thing missing right now from apollo client.
How to display values from database in real time without refreshing the webpage ?
How to update data with apollo client 3, for example, a user adds a category, how to make this category appear to all other pages? this function lists all the catagory from database:
async componentDidMount() {
setInterval(async()=>{
await client.query({
query: LISTER_CATEGORIE
},
)
.then((response) => {
this.setState({ ...this.state, categories: response.data.listerCategorie });
})
.catch((err) => console.error(err));
},3000)
}
this's the client:
export const client = new ApolloClient({
link: ApolloLink.from([
onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) graphQLErrors.map(({ message, locations, path }) => console.log(`[GraphQL error]:
Message: ${message},
Location: ${locations}, Path: ${path}`));
if (networkError) console.log(`[Network error]: ${networkError}`);}),
new createUploadLink({ uri: 'http://localhost:8080/graphql'})
]),
cache: new InMemoryCache({ typePolicies: {
Query: {
fields: {
categorie(existingData, { args, toReference }) {
return existingData ||
toReference({ __typename: 'Categorie', id: args.id });
},
.............
and this function adds a category:
async ajouterCategorie() {
await client.mutate({
mutation: AJOUTER_CATEGORIE,
variables: {
titre: this.state.newCategorie.titre,
presentation: this.state.newCategorie.presentation,
image: '',
dateCreation: new Date(),
file: this.state.file,
cours: []
}, refetchQueries: [
{ query: LISTER_CATEGORIE }
],
})
.then((response) => {
this.props.add(response.data.ajouterCategorie)
this.pushNotify("Catégorie Ajouté avec succès", 'success', "Ajout Categorie")
})
.catch((err) => console.error(err));
this.handleClose()
}
i used ComponentDidUpadate but it not worked too. Thank you in advance.
Summary: Using Apollo Client 3's Reactive Variables API (docs/blog post coming soon), we can store the entire application state locally (and optionally persist it using local storage).
Great!
What will be the best strategy to make the local state persisting (all the local state and only the local state), without having to wrap each write operation?
A good real world 'use case' would be a shopping cart. below is a typical result object for a shopping cart.
The goal here is to set a local variable called "user_selected_qantity" with the shopping cart remote data. and initialize a default value for it. here user should be able to increment and decrement "user_selected_qantity" for the given product. becuase evertime a user increments qty for the product it should not have to go to the server right. I hope i'm explaining this correctly
{
"data": [
{
"id": 1,
"__typename": "shoppingCart",
"userId": 33,
"productId": 25,
"productName": "some name",
"stock": 23,
"price": 50,
"user_selected_qantity": 23 <-------- Local Field,
"is_slected": true <-------- Local Field
}
...
]
}
This can be achieved seamlessly using two ways.
1- putting the data in to the component "state" and manipulating it.
2- putting the data in to "Redux or other state management library" and manipulate it.
By doing so. aren't we not duplicating the data? one in the redux and one in the cache. should I have to update both?
I was hoping to know the best practice for this use-case using ApolloV3 stuff.
It would be great if we also have examples in JSX. I don't know typescript and would like to save myself from the hassle of learning it for now.
Also, I am having a hard time understanding on how to convert my existing redux based react code to Apollo Client 3.
Like,
Is there any tutorial which may walk me through on converting the existing redux based app code to AC3 (NOT ac2)?
Edit:
Few more things I would like to understand -
Query
and a custom type like Product
when we define typePolicies? Is Query something global?I have a project (not publicly available) that's using the same patterns shown in the apollo-local-state
example. During development with HMR setup, components using the useQuery
hook fail to receive updates when the mutation function is ran after an HMR update. Everything works fine before the HMR update, and a page reload fixes it after the update, but that defeats the purpose of HRM of course... is this a known issue? I haven't been able to find anything regarding this yet.
I haven't had a chance to create a simple example repo or codesandbox to show the issue, but wanted to ask here just in case it's a known issue.
I'm getting the below error don't know why and what's happening, how get over it? I'm using TS
/test/ac3-state-management-examples/apollo-local-state/src/tests/createMockReactiveVar.ts
TypeScript error in /test/ac3-state-management-examples/apollo-local-state/src/tests/createMockReactiveVar.ts(11,3):
Property 'onNextChange' is missing in type '(newValue?: T | undefined) => T' but required in type 'ReactiveVar<T>'. TS2741
9 | let currentValue: T | undefined = defaultValue;
10 |
> 11 | return function mockReactiveVar (
| ^
12 | newValue?: T
13 | ) : T {
14 | if (newValue) {
To-do's are great for understanding the power and simplicity of Ac3 brings to development, but I would love to see an example like HackerNews implementation where there's a proper folder structure and best practices on splitting files that's
need usually in a more complex project.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.