Coder Social home page Coder Social logo

ac3-state-management-examples's Introduction

Archival

This repo was archived by the Apollo Security team on 2023-05-26

Please reach out at [email protected] with questions.

Apollo Client 3 State Management Examples

Learn how to use AC3 for local and remote state management

About

Apollo Client 3 is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server.

We have found that it can be challenging for developers coming from another state management library (like Redux) to fully grasp the AC3-way of doing things.

What we're building

This repo contains several versions of the same Todo app, both Apollo Client and Redux examples, to demonstrate best practices on using Apollo Client to build applications using solely local state in addition to the real-world remote state use case.

Examples

Apollo Local State Example

Summary: Using Apollo Client 3's Reactive Variables API (docs here, blog post here), we can store the entire application state locally (and optionally persist it using local storage).

Check out the local state example.

Apollo Remote State Example

Summary: Hooking Apollo Client up to a remote GraphQL API, the client-side cache is smart enough to automatically update the cache after most mutations successfully complete. For mutations that perform interactions against arrays or have additional client-side side-effects, we can help the cache decide what to do next by writing our update logic in the useMutation's update function. This approach uses the writeQuery and readQuery APIs which are recommended for those starting out with Apollo Client.

Check out the remote state example

Apollo Remote State Advanced Cache APIs Example

Summary: This example is the same as the previous remote state example, except that this time, we're using the new AC3 cache manipulation APIs: cache.modify and cache.evict. This approach is recommended for users who are comfortable with how cache normalization works in Apollo Client and who want direct control over the cache.

Check out the remote state (advanced cache APIs) example

Apollo Remote State (No Relay) Example

Summary: This example is the same as the previous remote state example, except that it doesn't use a Relay-style GraphQL schema. This is mostly used for presentations to keep code succinct.

Check out the remote state (no-relay) example

Redux Local State Example

Summary: The Redux architecture provides us with a well-defined mental model for how to update state in an immutable way. We've provided this example in order to compare how to accomplish the same tasks in AC3 and in Redux.

Check out the local state (with Redux) example

ac3-state-management-examples's People

Contributors

abernix avatar dependabot[bot] avatar jaknas avatar lifeeric avatar peakematt avatar rileymshea avatar stemmlerjs avatar toddpla avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ac3-state-management-examples's Issues

Strategy to make the local state persisting

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?

Persisting cache to localstorage

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.

Property 'onNextChange' is missing in type

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) {

JSX examples - Moving from Redux to Apollo Client 3

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,

  • How do I change my reducer code to make it work with AC3?
  • How do I migrate my reselect/actions/constants code to AC3?
  • I have multiple async polling in saga to fetch data (Time series graphs updating every 10 seconds). Can I migrate that as well?
  • I need to make requests to GraphQL end-point as well as REST end-points hosted on another domain. How can achieve both? Create multiple AC3 clients?

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 -

  • What is the difference between Query and a custom type like Product when we define typePolicies? Is Query something global?

Real-world example?

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.

Looking for example with remote data combined with local data

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.

Reactive variables and HMR (hot module reloading) / fast-refresh

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.

How to display values from database in real time with apollo client 3 and react js?

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.