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

Viewed 52

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 categories from the 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 is 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 either.

Thank you in advance.

0 Answers
Related