search

Home  >  Q&A  >  body text

Troubleshooting: Initial login and website loading issues

<p>I have a problem using Vue Apollo and Vuex in my Vue application, so when I log into the website for the first time, the web page is empty i.e. does not contain events and authentication, but when I use When the refresh button refreshes the site, all events load and the authentication is visible even in the network tab.Please can someone tell me what I'm doing wrong?</p> <p><strong>graphql.js</strong></p> <pre class="brush:php;toolbar:false;">import { ApolloClient } from 'apollo-client'; import { HttpLink } from 'apollo-link-http'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { createApolloProvider } from '@vue/apollo-option'; import { onError } from '@apollo/client/link/error'; onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) graphQLErrors.map(({ message, locations, path }) => console.log( `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`, ), ); if (networkError) { networkError.message = networkError.result.errors[0].debugMessage console.log(`[Network error]: ${networkError}`) }; }); const XPORTAL = process.env.VUE_APP_XPORTAL function getHeaders() { const headers = {}; const token = window.localStorage.getItem("apollo-token"); if (token) { headers["Authorization"] = `Bearer ${token}`; } headers["x-portal"] = XPORTAL; headers["X-Requested-With"] = "XMLHttpRequest"; return headers } let GRAPHQL = process.env.VUE_APP_API_GRAPHQL let GRAPHQLPORTAL = process.env.VUE_APP_API_GRAPHQLPORTAL const graphqlClient = new ApolloClient({ link: new HttpLink({uri: GRAPHQL, headers: getHeaders()}), cache: new InMemoryCache() }); const graphqlClientPortal = new ApolloClient({ link: new HttpLink({ uri: GRAPHQLPORTAL, headers: getHeaders()}), cache: new InMemoryCache() }); export function provider() { const provider = createApolloProvider({ clients: { graphqlClient, graphqlClientPortal }, defaultClient: graphqlClient, defaultOptions: { $query: { fetchPolicy: 'cache-and-network' } }, }) return provider }</pre> <p><strong>main.js</strong></p> <pre class="brush:php;toolbar:false;">import { createApp } from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import * as apolloProvider from "../../events.live/src/utils/graphql"; const app = createApp(App); app.use(apolloProvider.provider) app.use(store); app.use(router); app.mount("#app");</pre> <p><strong>index.js</strong></p> <pre class="brush:php;toolbar:false;">import { provider } from "../utils/graphql"; actions: { async fetchLogin({ commit, state }) { return new Promise(async (resolve, reject) => { commit('loadingStatus', true) try { const response = await provider().clients.graphqlClient.mutate({ mutation: gql`mutation Login($email:String!, $password:String!) { login(email:$email, password:$password){ token } }`, variables: { email: state.login.email, password: state.login.password } }) const token = response.data.login.token commit('setToken', token) localStorage.setItem('apollo-token', token) } catch (error) { commit('loadingStatus', false) } resolve() }) }, { async fetchEvents({ commit }) { try { const response = await provider().clients.graphqlClientPortal.query({ query: gql` query LiveEvents($limit: Int!, $page: Int!){ liveEvents(pagination:{limit:$limit, page:$page}, order:{startsAt:{direction: DESC}}){ total, data{ id, name, stub, description, mainImage{ id, uri }, location, type, layout chat, liveStream{ endsAt, startsAt } } } } `, variables: { limit: 12, page: 0 }, }); commit('allEvents', response.data.liveEvents.data); } catch (error) { console.log('error-message', error.graphQLErrors) } },</pre> <p><br /></p>
P粉891237912P粉891237912474 days ago544

reply all(1)I'll reply

  • P粉413307845

    P粉4133078452023-08-04 12:37:22

    This is my solution.

    import { provider } from "../utils/graphql";
    
    actions: {
      async fetchEvents({ commit }) {
        try {
          const response = await provider().clients.graphqlClientPortal.query({
            query: gql`
              query LiveEvents($limit: Int!, $page: Int!){
                liveEvents(pagination:{limit:$limit, page:$page}, order:{startsAt:{direction: DESC}}){
                  total,
                  data{
                    id,
                    name,
                    stub,
                    description,
                    mainImage{
                      id,
                      uri
                    },
                    location,
                    type,
                    layout
                    chat,
                    liveStream{
                      endsAt,
                      startsAt
                    }
                  }
                }
              }
            `, variables: {
              limit: 12,
              page: 0
            },
          });
          commit('allEvents', response.data.liveEvents.data);
        } catch (error) {
          console.log('error-message', error.graphQLErrors)
        }
      },
    
      async fetchLogin({ commit, state }) {
        return new Promise(async (resolve, reject) => {
          commit('loadingStatus', true)
          try {
            // Load the events before logging in
            await dispatch('fetchEvents');
            const response = await provider().clients.graphqlClient.mutate({
              mutation:
                gql`mutation Login($email:String!, $password:String!)
                {
                  login(email:$email, password:$password){
                    token
                  }
                }`, variables: {
                email: state.login.email,
                password: state.login.password
              }
            })
            const token = response.data.login.token
            commit('setToken', token)
            localStorage.setItem('apollo-token', token)
          } catch (error) {
            commit('loadingStatus', false)
          }
          resolve()
        })
      },

    reply
    0
  • Cancelreply