What is the best way to trigger the Vue.js ApolloClient middleware to run again?

Within my main.js, I have implemented a code snippet that checks if a certain item exists in the localStorage. If it does, the code will add an Authorization header to the ApolloClient setup using middleware.

However, if a new item is added to the localStorage at a later time, it will not be recognized by the middleware in main.js. A complete page refresh becomes necessary to ensure the new item is picked up and acknowledged.

The question arises: How can I re-run the main.js script (if this is indeed the solution) from a method within a different component responsible for user sign-in?

Here is a glimpse of my main.js:

import Vue from 'vue'
import ApolloClient, { createNetworkInterface } from 'apollo-client'
import VueApollo from 'vue-apollo'
import App from './App'
import router from './router'
import store from './store'

const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/MY-ID-HERE' })
const requestToken = localStorage.getItem('TOKEN')

networkInterface.use([{
  applyMiddleware (req, next) {
    if (!req.options.headers) {
      req.options.headers = {}
    }
    req.options.headers['Authorization'] = requestToken ? `Bearer ${requestToken}` : null
    next()
  }
}])

const apolloClient = new ApolloClient({
  networkInterface
})

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
})

Vue.use(VueApollo)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App />',
  components: {
    App
  },
  apolloProvider,
  router,
  store
})

I hope the intentions behind my approach are clear. Thank you for your understanding.

Best regards

Answer №1

To address the issue you're facing, it is recommended to relocate your requestToken declaration within the applyMiddleware function. By doing this, you will ensure that local storage is checked for a token each time a request is initiated. If not done as suggested, the check will only happen once during page load, resulting in the behavior you mentioned.

networkInterface.use([{   applyMiddleware (req, next) {
    const requestToken = localStorage.getItem('TOKEN')
    if (!req.options.headers) {
      req.options.headers = {}
    }
    req.options.headers['Authorization'] = requestToken ? `Bearer ${requestToken}` : null
    next()   } }])

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 React JS to dynamically adjust the z-index upon clicking a component

My goal is to create a functionality where clicking on a box will move it to the top, with the previous box now underneath. For a better understanding, please refer to the following code snippet. https://codesandbox.io/s/optimistic-payne-4644yf?file=/src/ ...

Check if any element from the first array exists in any nested array of the second array and return a Boolean

Having two distinct types of arrays, firstArrayObject = [{name: "sample", number: 23}, {name: "sample2", number: 25}]. The second object takes the form of secondObject = {someAttribute: bla, numbers: [23, 26, 27, 28} My goal is to det ...

Searching for an Angular 7 alternative to Vue.js's "nextTick" function

In my Angular 7 project, I'm facing a situation where I need to automatically scroll to a specific section on the page after it has been fully rendered. The section is initially hidden using ngif and should only be scrolled to once it is visible in th ...

Displaying subsets of data based on the identifier of the primary array

In my JSON file, I have an array containing various categories and their respective subcategories. { "Women": [ { "id" : 1, "name" : "See All", &q ...

Require assistance in accurately assigning a date to a Date[] in Typescript Array without altering current elements

In my current code, I have a loop that verifies if a date is a holiday and then adds it to an array. The issue I'm facing is that whenever I assign a new element to the array, all previous data in the list gets updated to the latest element. Here&apos ...

What causes my React app menu to unexpectedly open while simply updating the state without any CSS modifications?

In the Header component, there is a button that triggers the toggleNav function in context.js when clicked. This function changes the state of isNavOpen from false to true, resulting in the opening of the navigation. Surprisingly, there doesn't appear ...

Iterate through a JSON object using JavaScript, with distinct keys but the same object structure

Hello, I'm currently in the process of creating a slider using images sourced from a json file. Here is the json structure that I am working with: { "info":[ { "slide1":[ { "title" ...

Tips for displaying the HTML content within the autocomplete box

My situation involves a text input and an HTML form where users can submit their name to retrieve information. I am using AJAX to display the usernames dynamically. <div class="hidesearch" id="search" style="width:"400px;"> <inp ...

Utilize PHP to import an HTML file with JavaScript code into MySQL database

I've been attempting to use JavaScript to retrieve my location, but I'm facing an issue where when I click submit, the data is not getting entered into the page action.php. geolocation.php <form action="action.php" method="post"> < ...

Rendering in React by cycling through an array and displaying the content

I have been working on displaying two arrays. Whenever the button is clicked, a new user is generated and added to the array. My goal is to render the entire array instead of just the newest entries. I've attempted various methods but haven't had ...

Analyzing an HTTP response containing a Content-Type header specifying image/jpeg

Currently, I am developing my first web application and the task at hand involves loading an image from a database and sending it to the client for display. On the server side, I have the following code: res.setHeader('Content-Type', pic.mimetyp ...

Tips for Setting Up Next.js 13 Route Handlers to Incorporate a Streaming API Endpoint via LangChain

I am currently working on establishing an API endpoint using the latest Route Handler feature in Nextjs 13. This particular API utilizes LangChain and streams the response directly to the frontend. When interacting with the OpenAI wrapper class, I make sur ...

Issue with text input field causing the Enter key to not create a new line

In the example above, the text is placed in the middle of the text area. Here is the CSS code : .form-control { height: 300px; display: block; width: 100%; padding: 0.375rem 0.75rem; font-size: 1rem; font-weight: 400; line-heig ...

"Exploring the world of digital art with JavaScript through canvas and canvas

How can I adjust the value of a canvas arc? The input accepts larger values, but not smaller ones. var btn = document.querySelector(".btn"); btn.addEventListener("click", () => { var inputVal = document.querySelector(&q ...

The getInitialProps function in Next.js React components does not automatically bind props

When building applications with Next.js, you have the opportunity to leverage a server-side rendering lifecycle method within your React components upon initial loading. I recently attempted to implement this feature following instructions from ZEIT' ...

Retain datatable search value upon page refresh in vue.js

Is there a way to maintain the filtered values on the page even after it's refreshed? https://i.sstatic.net/HCMLJ.pngI want to ensure that the filtered items show the last selected values when I return to this view. <vk-datatable :colum ...

What could be causing an error when trying to use a computed property?

Currently utilizing Vuex. Within the Getter Foo function, I am returning two values within an array: return ["Try Again"] or return ["Data result", data]. In the computed property, I am checking the array length and returning based on ...

Adjust the alignment of text on both ends of the HTML5 canvas

Is there an easier way to align text on both sides of a canvas element besides using CSS? The link below might provide some insight: https://github.com/nnnick/Chart.js/issues/114#issuecomment-18564527 I'm considering incorporating the text into the d ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

How can I apply a blurred effect to the background image of a jumbotron in Bootstrap-vue without affecting the clarity of the text overlay

I need help figuring out how to blur the background image of my jumbotron without blurring the text on top. <b-container fluid class="text-center"> <div> <b-jumbotron class="jumbotron"> <p style=& ...