Is Apollo Client in NextJS failing to refresh data post mutation?

On this page, you can create a new User

const [createType, { loading, data }] = useMutation(CREATE_USER_CLASS) //mutation query

const createUserClass = async (event) => {
    event.preventDefault();
    try {
      const { data } = await createType({
        variables: {
          userClassName,
        },
        refetchQueries: [{ query: STACKINFO }],
        options: {
          awaitRefetchQueries: true,
        },
      });
      setNotification({
        message: 'User class created successfully',
        code: 200,
      });

      handleClose();
    } catch (e) {
      setNotification({ message: e.message, code: 400 });
      handleClose();
    }
  };

I've noticed that the API is being called twice in the network tab, which isn't ideal. Although I can see the new data added, the page doesn't seem to refresh. Any suggestions on how to fix this issue would be much appreciated.

Answer №1

When faced with a similar issue, I stumbled upon your question. Depending on the version of Apollo Client you are using, instead of relying on the refetchQueries() method, consider utilizing update() to clear the cache and inform the UI of any changes. Here's an example:

createType({
    variables: {
      userClassName,
    },
    update(cache) {
       cache.modify({
          fields: {
           // Field you want to udpate
          },
       });
     },
  })

For further information, refer to the official documentation page: https://www.apollographql.com/docs/react/data/mutations/#:~:text=12-,update

Hope this solution proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing ng-href in Angular.js Template: A Guide

I am attempting to develop a simple Single Page Application (SPA) with just one index.html file that includes templates. However, I encountered an issue with the ng-href directive: <a ng-href="#/myPage">myPage</a> This works fine in index.h ...

Interoperability between AngularDart and AngularJS

Discovering the Dart language and AngularDart after working with AngularJS has been exciting. However, my biggest concern is whether AngularDart supports all the amazing modules that AngularJS offers. I haven't been able to find any information on whe ...

Outputting PHP variables in JavaScript is a common practice used to pass

I am struggling to use a variable in my JavaScript code. I have attempted a few methods but none seem to work. The variable I need to include in the JavaScript is option-<?php echo $option['product_option_id']; ?> Below is my current Java ...

Customize the text displayed in a dropdown menu in Angular Material based on the selection made

I am working with a multi-select dropdown menu that includes an option labeled "ALL" which, when selected, chooses all available options in the list. My goal is to display "ALL" in the view when this option is chosen or when the user manually selects all t ...

Loop through each instance of a data record in a JSON document using Vue's v-for directive

I am currently working on a project that involves extracting data from a website that monitors traffic jams and maintenance work. My goal is to specifically retrieve information about traffic jams and display them individually. The code I am using utilize ...

Creating interactive button groups with responsive design in a Material UI and ReactJS web application

Is it possible to make ButtonGroup Buttons responsive? I heard about an attribute called "Orientation" in material-ui's ButtonGroup, but I'm not sure how to use it with media queries for changing orientation based on the device width. I'm st ...

The Chevron icon is not pointing downwards even though it has already gone upwards

I want to toggle a chevron icon, but nothing seems to be happening. $("span:last").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up"); When I add this code below the slideToggle function without an if-else section, the icon changes to ...

Filtering Sails.js query model based on a collection attribute

Imagine I have these models set up in Sails.js v0.10: Person.js module.exports = { attributes: { name: 'string', books: { collection: 'book', via: 'person' } } }; Book.js module.exports = { ...

JavaScript: Specialized gravity diagram

To better understand the issue I am experiencing, please take a look at the image linked below: The concept and problem I am facing is related to creating a weight chart similar to the one shown in the picture or on this site , here is the description of ...

Is there a way to click on a button and have its background color change randomly each time?

I am facing an issue with a button on my HTML page. When the button is clicked, I want its background color to change to a random different color. However, despite trying various sources, I am unable to get it right. It seems like I am not placing the code ...

failure to properly assign a property during model update in mongoose

My BaseSchema contains logic that should set values for two properties when a new Model is created: schema.pre("save", function (next) { if (!schema.isNew) { this.createDate = new Date(); this.createBy = "kianoush"; } next(); }); If updating, ...

Tips for optimizing the "framerate" (setInterval delay) in a JavaScript animation loop

When creating a JavaScript animation, it's common practice to use setInterval (or multiple setTimeouts) to create a loop. But what is the optimal delay to set in these setInterval/setTimeout calls? In the jQuery API page for the .animate() function, ...

Vue JS encountering Slack API CORS issue while using axios

I am currently developing an application using Capacitor JS & Nuxt JS to interact with the Slack API for setting my Slack status. I have successfully created a Slack App and obtained a xoxp- token, which works perfectly when sending a POST request via Post ...

Attempting to access an avatar image via an API, only to encounter an error message indicating that the avatar is not defined

userData is a function that retrieves user data from an API using getUserByChainAccount. The username required by getUserByChainAccount is dynamically fetched from buyer. I'm trying to access the avatar, but I keep encountering the error message Unha ...

Error: The value being evaluated in document.getElementById(x).style is not an object and is not supported

Desired Outcome for my Javascript: I am working with a div that includes an "onmouseover='getPosition(x)'" attribute which can be dynamically added and removed through my javascript by clicking a specific button. The function 'getPosition() ...

Can anyone tell me what I might be doing incorrectly when comparing these two timestamps?

I am facing an issue while comparing two timestamps in Angular. Here is the code snippet: public isAuthenticated(): boolean { const token = localStorage.getItem('Fakelife'); const lifetime = new Date().getTime(); const result = life ...

What could be the reason for the sudden failure of my jQuery + AJAX functionality?

As a novice in JavaScript/jQuery/AJAX, I have a suspicion that the issue lies in some typo that I may have overlooked. Everything was working perfectly, but when I made some edits, the hide() + show() methods stopped functioning (I tested it on both Firefo ...

leveraging jQuery mobile for asynchronous requests

I've been attempting to print a jQuery mobile element using ajax, but I'm running into an issue where the result isn't being encoded as jQuery mobile is intended to do. Below is a simplified excerpt of the JavaScript code responsible for t ...

Custom Component in React Bootstrap with Overflowing Column

I am working on a custom toggle dropdown feature in my React application: import React from 'react'; import 'react-datepicker/dist/react-datepicker.css'; const DateRange = props => ( <div className="dropdown artesianDropdo ...

Showing a collection of objects in a React component

**Recently started learning React and Node, and decided to fetch data into a functional component by following various tutorials. I successfully set up the server, connected it to the database, and fetched the data in React as per the tutorial instruction ...