Search code examples
vuexapollo-clientnativescript-vuevue-apollo

Why there is no data after the first login?


Dear vue and apollo users;

I am dealing with the first time install problem.

When I first launch the app, I don't get results.

I am using ApolloClient, InMemoryCache, HttpLink from "apollo-boost"

I store my userID and JWT in ApplicationSettings(local storage)

How to set token dynamically?

Vue.use(VueApollo);
const httpLink = new HttpLink({
    uri: "https://sebapi.com/graphql"
});
const authLink = setContext((_, { headers }) => {
    // get the authentication token from ApplicationSettings if it exists
    var tokenInAppSettings = ApplicationSettings.getString("token");
    // return the headers to the context so HTTP link can read them
    return {
        headers: {
            ...headers,
            authorization: tokenInAppSettings
                ? `Bearer ${tokenInAppSettings}`
                : null
        }
    };
});
export const apolloClient = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
});

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

I have created a GitHub repo reproducing problem

and a youtube video of the problem

There is no error during login but after navigating to the list page for the first time I got following errors...

JS: [Vue warn]: Invalid prop: type check failed for prop "items". Expected Array, Object, got Undefined

JS: Error sending the query 'birds' ServerError: Response not successful: Received status code 400

IT SEEMS APOLLO DOES NOT HAVE userID during first query.

NOTE: You can easily clear user data by using yarn cl script

# debug app without HMR
yarn devn
# clear user data of app
yarn cl

Solution

  • Solution repo using vuex:

    https://github.com/kaanguru/data-firstlogin/tree/user-in-vuex

    Move userID into vue instance

    +welcome.vue+

    //const userId = ApplicationSettings.getNumber("userID");
    // I have moved userID into vue.
    
    export default {
      data() {
        return {
          birds:[],
          bird:{
            id: null,
            isim: "",
            bilezik: ""
          },
          userId: ApplicationSettings.getNumber("userID")
        };
      },
    
      apollo: {
        birds: {
          query: gql`
            query myBirds($userId: ID!) {
              birds(where: { user: $userId }) {
                id
                isim
                bilezik
              }
            }
          `,
          variables() {
            return {
              userId: this.userId,
            };
          },
        },
      },
    };