Trigger a page refresh when you revisit it

Currently, I am utilizing Nuxt in SPA mode and my page structure is set up like this:

pages

...

- users/
- - index
- - new
- - update/
- - - _id

...

I have a page dedicated to displaying a list of users along with a 'subpage' for adding new users.

On the users/index page, I fetch my users within the asyncData Hook as shown below:

async asyncData({ app: { apolloProvider }, store: { commit, dispatch } }) {
    
    const {
      data: { getAllUsers: { success, users, message } },
    } = await apolloProvider.defaultClient.query({
      query: getAllUsersGQL,
    })

    if(success) {
      await commit('user/setUsers', users, { root: true })
    } else {
      dispatch('snackbar/notify', { message: message, type: 'error' }, { root: true })
    }

  },

The functionality seems to be working fine. However, upon navigating to my users/new page, submitting the form, updating the store, and redirecting back to users/index, an unexpected behavior occurs.

The issue lies in not having the newly updated state displayed, but rather a cached or previous state. To tackle this, I've managed to make it function properly by using location.replace. Upon reloading the page, the state is accurately refreshed and updated.

Here's how I handle redirection on the users/new page:

    async save() {

      if(this.$refs.create.validate()) {
        this.loading = true
          
        delete this.form.confirm

        await this.createUserStore(this.form)

        this.$router.push(
          this.localeLocation({
            name: 'users',
          })
        )

        this.loading = false
        this.$refs.create.reset()
      }
    },

And here's how I refresh the state in Vuex:

export const mutations = {
    updateUsers: (state, payload) => {
        state.users = [...state.users, payload].sort((a,b) => a.createdAt - b.createdAt)
    },
}

This is how I pass data:

    computed: {
        ...mapGetters({
            storeUsers: 'user/getUsers',
            storeGetMe: 'auth/getMe',
        }),
    },
<v-data-table
    :headers="headers"
    :items="storeUsers"
    :search="search"
    item-key="id"
    class="elevation-1"
    dense
>
</v-data-table>

I have tried listing items using v-for as well, but without success. When I console.log the state, I can see all items present, functioning correctly.

What could possibly be causing the view from being updated?

If anyone has encountered a similar issue before, any suggestions would be greatly appreciated.

Answer №1

It is highly likely that the reason for this behavior is due to Apollo having its own caching system and by default, it prioritizes the cache with a 'cache-first' approach.

Why not give this a shot?

await apolloProvider.defaultClient.query({
  query: getAllUsersGQL,
  fetchPolicy: 'network-only',
})

Another insight

Here's an example of a dynamic GQL query that I previously crafted

test.gql.js

import { gql } from 'graphql-tag'
import { constantCase, pascalCase } from 'change-case'

export const queryCompanyBenefitInfo = ({
  benefitType,
  needCifEligibility = false,
  needActiveOnWeekend = false,
  needCompanyContribution = false,
  needAutoRenewed = false,
  needUnitValue = false,
}) => {
  return gql`
    query {
      CompanyBenefit {
        oneOfType(benefitType: ${constantCase(benefitType)}) {
          ... on Company${pascalCase(benefitType)}Benefit {
            ${needCifEligibility ? 'cifEligibility' : ''}
            ${needActiveOnWeekend ? 'activeOnWeekend' : ''}
            ${needCompanyContribution ? 'companyContribution' : ''}
            ${needAutoRenewed ? 'autoRenewed' : ''}

            ${
              needUnitValue
                ? `unitValue {
                    value
                  }`
                : ''
            }
          }
        }
      }
    }
  `
}

You can invoke it like so

import { testQuery } from '~/apollo/queries/test.gql.js'

...

await this.app.apolloProvider.defaultClient.query({
  query: testQuery({ benefitType: 'care', needCifEligibility: true }),
  fetchPolicy: 'network-only',
  errorPolicy: 'all',
})

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

In the world of web development with JavaScript, jQuery, and EasyUI, we often encounter situations where the parameter

function formatData_original() { // convert obj_num2.formatter = function(value, rec) { var baseStr='&nbsp;&nbsp;' + rec.s_date + '<a class="easyui-linkbutton" href="javascript:void(0);" plain= ...

Creating a Multilevel Dropdown Menu: A Step-by-Step Guide

I am curious about how to create a multilevel dropdown menu using Bootstrap 5 and vanilla JavaScript. I created an example based on the Bootstrap 5 dropdowns component documentation, but it did not display when I clicked on it. The issue seems to be relat ...

Issue with joining tables in query on Cordova Mobile app

I have 2 queries that will return results which I plan to use in JSON format. The first query is $query = "SELECT * FROM info_location WHERE location_id=".$id.""; and the second query $query = "SELECT t1.location_id,t1.street,t1 ...

Encountering an issue where props are receiving a value of undefined within a component that is

After receiving a JSON response from getStaticProps, I double-checked the data by logging it in getStaticProps. The fetch functionality is working smoothly as I am successfully retrieving the expected response from the API. import Layout from '../comp ...

Firefox has various problems, but it functions flawlessly in Chrome without any problems

I seem to be encountering various issues in Firefox that do not occur in Chrome. 1) I am facing a TypeError: response.body is null. 2) Another issue arises when uploading images, resulting in a TypeError: Argument 1 of FormData.constructor does not imple ...

VueJS: Incorporating a Computed Property within a v-for Loop

Is there a way to utilize computed properties in lists while working with VueJS v2.0.2? Check out the HTML snippet below: <div id="el"> <p v-for="item in items"> <span>{{fullName}}</span> </p> </div> A ...

The npm run watch command in Laravel 7 is not functioning properly with Node v10.15.0 and NPM v6.5.0

I encountered a problem while using Laravel and Vue. After attempting to compile everything with npm run watch, I started receiving the following error messages: It seems that additional dependencies need to be installed. Please wait a moment. Running: y ...

Verify the operation within a pop-up box using ruby watir

Is it possible to confirm a modal dialog window in Internet Explorer using Ruby Watir? Here is the JavaScript code for the modal dialog: jQuery('#yt100').on('click', function(){return confirm('modal dialog window text');}); ...

A comprehensive guide on iterating through an array in JavaScript

Currently, I am facing an issue while trying to iterate over an array of Objects in React that have been fetched from Django. The object is stored as an array, but when attempting to map it, I encounter a typeerror stating "cannot read property map of unde ...

Issue with second button in Angular Onclick() not been resolved

I'm experiencing an issue with the onClick() methods in my code. There are two onClick() methods present on the UI, but when I click on the second one, it does not call the method while the first one does. I am struggling to figure out why this is hap ...

Can you explain the function of "app.router" in the context of Express.js?

When looking at the default app.js file generated by express.js, I came across the following line: ... app.use(app.router); ... This particular line of code has left me perplexed for a couple of reasons. First, upon consulting the express api documentati ...

Tips for validating a form with the assistance of jQuery

While there are multiple answers out there for this particular question, I am specifically interested in validating an entire form with dynamic input fields sourced from a database similar to Google Forms. HTML <div class="rs_card"><spa ...

What does dist entail?

I am currently utilizing gulp to create a distribution folder (dist) for my Angular application. After consolidating all the controllers/services JS files and CSS, I am now faced with handling the contents of the bower folder. In an attempt to concatenat ...

Headers cannot be sent to the client after they have already been set in Axios within Next.js

For additional discussion on this issue, please refer to the GitHub thread at - https://github.com/axios/axios/issues/2743 In my Next.js project, I am using Axios and occasionally encounter an error related to interceptors when returning a Promise.reject. ...

Last month's display is currently unidentified

function calculateTime() { var Make_It_12_Hour = true; var currentTime = new Date(); var hour1 = currentTime.getHours() - 1; var hour2 = currentTime.getHours(); var hour3 = currentTime.getHours() + 1; var minutes = currentTime.getM ...

The object prototype can only be an instance of an Object or null; any other value will

While attempting to create a codesandbox in order to replicate a bug, I encountered an additional issue. You can view my codesandbox here: https://codesandbox.io/s/vue-typescript-example-o7xsv The error message states: Object prototype may only be an ...

Struggling to add a line break in my code

class Test extends React.Component{ state={name: "John", numTimes: 2}; render() { let output = "" for (let i = 1; i <= this.state.numTimes; i++) { let evenOdd = i % 2 if (evenOdd === 0) { output += i + ". Hello " + this.state.name + ...

Mastering the map() function in Vue.js 2

As I start learning vue.js, I am facing some challenges. I need to implement a dictionary analog in JavaScript, known as a map. However, I'm unsure of where to define it. The map should be utilized in both the checkDevices() method and within the HTML ...

How can I choose the div that is in the same container class div as this using Jquery?

As I cycle through data within a foreach loop, each iteration populates a container class as shown below: foreach($resultarray AS $value){ $filename = substr($value['img_file_name'],9); $cat_id = $value['cat_id']; ...

Trouble displaying Bar Graph in chart.js using PHP

I am facing a challenge with creating a bar graph using chart.js that loads data from a PHP array via ajax. The data is successfully loaded through ajax, as confirmed in the console, but I am unable to display it on the graph. Here's what I see in the ...