How to use Graphql Vue Apollo on older IOS / older browser? - javascript

I just realize and noticing that my vue app doesn't work well on some older browsers (ios 9 for example). I used the vue-apollo to get data from graphql api using django graphene , but it doesn't event get called on the first load when i debug it.
Previously i get error like "fetch is not found globally", but then i already fix it by adding "unfetch" to the ApolloClient config. But i still can't see on xhr network the api get called. I haven't try with isomorphic-fetch
Here's my code for the apollo client config:
// src/utils/graphql.js
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import fetch from 'unfetch'
export default new ApolloClient({
// Provide the URL to the API server.
link: new HttpLink({ uri: '/api/', fetch: fetch }),
// Using a cache for blazingly
// fast subsequent queries.
cache: new InMemoryCache(),
connectToDevTools: true
});
and i specify it like so in the main.js
import apolloClient from '../utils/graphql'
import VueApollo from 'vue-apollo'
Vue.use(VueApollo);
Vue.config.silent = true
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
defaultOptions: {
$loadingKey: "loading"
}
})
This is example of the apollo that i use inside the main.js as well using the smart query:
apollo: {
currentUser: {
query: GET_LOGGED_USER,
skipQuery() {
return this.skipUser
}
}
}
How can i make it work on ios 9 / any older browser?

Ok, after debugging it for two days, I finally found out the issue. So it turns out that i need to add and configure babel/polyfill as well in order to make it works, and add it to the entry point of my app.
Hope everyone who has the same issue can learn from my mistake lol

Related

Apollo Client "Named export 'remove' not found"

I'm attempting to create an apollo client plugin for a Nuxt 3 application. It's currently throwing an error regarding a package called ts-invariant:
file:///Users/[my name]/Repositories/[project]/node_modules/#apollo/client/utilities/globals/fix-graphql.js:1
import { remove } from "ts-invariant/process/index.js";
^^^^^^
SyntaxError: Named export 'remove' not found. The requested module 'ts-invariant/process/index.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'ts-invariant/process/index.js';
const { remove } = pkg;
at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:181:5)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
at async __instantiateModule__ (file:///Users/[my name]/Repositories/[project]/.nuxt/dist/server/server.mjs:4550:3)
[vite dev] Error loading external "/Users/[my name]/Repositories/[project]/node_modules/#apollo/client/core/index.js".
at file://./.nuxt/dist/server/server.mjs:3170:289
at async __instantiateModule__ (file://./.nuxt/dist/server/server.mjs:4550:3)
I feel like I know enough about this error to know it has something to do with how Nuxt 3 deals with ESM, but I can't be for certain.
Here's the nuxt plugin:
plugins/apollo-client.js
import { defineNuxtPlugin } from "#app"
import { ApolloClient, InMemoryCache } from "#apollo/client/core"
import { DefaultApolloClient } from "#vue/apollo-composable"
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
const apolloClient = new ApolloClient({
uri: config.PUBLIC_API_ENDPOINT,
cache: new InMemoryCache(),
})
nuxtApp.vueApp.provide(DefaultApolloClient, apolloClient)
})
In a normal scenario, I might use the nuxt-apollo community module, but it is currently afk regarding a nuxt 3 port, so a plugin it is.
Here's some documentation I relied on for my plugin:
https://v4.apollo.vuejs.org/guide-composable/setup.html#vue-3
https://v3.nuxtjs.org/docs/directory-structure/plugins
Solved by including #apollo/client and ts-invariant/process into the nuxt build transpile like so:
// nuxt.config.js
// ...
build: {
postcss: {
postcssOptions: require('./postcss.config.js')
},
transpile: [
'#apollo/client',
'ts-invariant/process',
],
},
// ...
I think I've pinpointed the underlying issue. Apollo Client (3.5.10 at the time of writing early 2022) is using "module":"index.js" to declare the path of the ESM exports.
However it seems that Webpack 5 based bundlers do not support this. Using exports in the package.json fixes it for good for me.
You should upvote this feature request.
And here is my palliative until then, using a small script to alter the package.json.

NextJS i18n - Locale getting undefined

I'm trying to migrate my website to NextJS, and I'm having trouble to do some internationalization.
I'm following the tutorial from Documentation itself, but my locale in the inspector is coming up as undefined.
What i'm doing wrong?
I'm using the latest version of nextJS.
Im trying to get some info from console.log.
console.log("Locale: " + locale);
console.log(router);
and it prints:
next.config.js
module.exports = {
i18n: {
locales: ['en-US', 'pt-BR'],
defaultLocale: 'pt-BR',
},
}
/pages/index.js
import Head from 'next/head'
import { useRouter } from 'next/router'
import pt from '../locale/index/pt'
import en from '../locale/index/en'
export default function Home() {
const router = useRouter();
const { locale } = router;
const t = locale === 'pt' ? pt : en;
return (
<div className="container">
<Head>
<title>{t.title}</title>
</Head>
</div>
)
}
/locale/pt.js
export default {
title: "Teste Portugues."
}
/locale/en.js
export default {
title: "Test English"
}
Some random info:
NextJS Version: 12.0.4
Chrome Version: 96.0.4664.55
Node Version: 17.0.1
UPDATE: I did a restart of my computer, and after this, 3 days later, when i use console.log({locale}), it get my pt-BR locale normally.
(And i did nothing more)
So, i'll close the thread. Thanks anyway!
This seems to be a bug in older versions of Next.js. yesterday, I had a similar issue, and after upgrading Next, React, and React-dom to their latest version, it worked like charm!.
Just restart the server. If the next.config.js file is modified, you have to restart your server for the changes to take effect

Nuxt.Js axios not using baseURL despite it being set correctly

I want to call an API in asyncData()
async asyncData({ $axios, params, store }) {
let itemUUID = params.item;
let item = await $axios.get("/item/" + itemUUID);
return {item};
}
Problem: Axios is still making the request on http://localhost:3000
if I do a console.log($axios.defaults.baseURL) the correct baseURL of my API is printed.
This also works if I use my store action & make the call by using this.$axios
I am using #nuxtjs/axios 5.13.1 with Nuxt 2.15.6 in SSR mode and configured it with the correct baseURL in the nuxt.config.js
Interestingly, if I edit my page content and a hot module reload is triggered, the correct URL is used. Maybe the question should be if Axios is triggered in the right time, on the server?
Edit: I checked the request that was made on HMR and this was triggered in the client.js.
If I call my store inside the created() hook the request gets executed successfully.
My nuxt.config.js:
publicRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL
}
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL,
}
},
I'm not sure what is the NODE_TLS_REJECT_UNAUTHORIZED=0 thing doing but your frontend configuration (Nuxt) is working well so far.
Sorry if I cannot help on the Express part.
Maybe try to setup HTTPS locally on Nuxt: How to run NUXT (npm run dev) with HTTPS in localhost?
TLDR; This was not related at all - I forgot to set the auth token for my backend. At the time of axios init it's not present. $axios object doesn't have auth - backend fails.
On page load the nuxt function nuxtServerInit() is used to get the auth token out of the acces_token cookie.
I am using a plugin to initialize Axios - with the token from the store.
But of couse the token is not present at the time axios is initialized as nuxtServerInit is called after plugin init.
In my axios.js plugin I changed:
export default function({ app, error: nuxtError, store }) {
const token = const token = store.state.user.token;
app.$axios.setToken(token, "Bearer");
}
to;
export default function({ app, error: nuxtError, store }) {
const token = app.$cookies.get("access_token");
app.$axios.setToken(token, "Bearer");
}
Now the token is present & used for every request happening server-side.

Auth0 authentication with Gridsome server side rendering breaks with window is undefined

I've implemented the auth0 Vuejs according to their tutorial with Gridsome, and it worked fine in develop.
However, when I run gridsome build the build fails because window is undefined in a server context.
I've found a few issues in Auth0-js lib that claim that Auth0 should only be used in client side, however, due to the way Gridsome works, I can't seem to find a way to only load the Auth0-js in client side.
Gridsome has main.js where I would add plugins, and in there, I define the routing for authentication.
Main.js
import AuthServicePlugin from '~/plugins/auth0.plugin'
import auth from '~/auth/auth.service'
export default function (Vue, { router, head, isClient }) {
...
Vue.use(AuthServicePlugin)
//Handle Authentication
router.beforeEach((to, from, next) => {
if (to.path === "/auth/logout" || to.path === "/auth/callback" || auth.isAuthenticated()) {
return next();
}
// Specify the current path as the customState parameter, meaning it
// will be returned to the application after auth
auth.login({ target: to.path });
})
Based on a Gatsbyb.js auth0 implementation tutorial, I've tried to exlude auth0-js from webpack loading with null-loader
gridsome.config.js
configureWebpack: {
/*
* During the build step, `auth0-js` will break because it relies on
* browser-specific APIs. Fortunately, we don’t need it during the build.
* Using Webpack’s null loader, we’re able to effectively ignore `auth0-js`
* during the build. (See `src/utils/auth.js` to see how we prevent this
* from breaking the app.)
*/
module: {
rules: [
{
test: /auth0-js/,
use: 'null-loader',
},
],
},
I would love to get some ideas about how to include and load Auth0 only in client side context with Gridsome
I had the same problem with using Firebase Authentication with Gridsome.
It seems that code in the created() lifecycle hook gets executed in the Gridsome build process (which is a server environment), but code in the mounted() lifecycle hook only executes in the browser!
The solution was to put all the code that should only run in the client in the mounted lifecycle hook.
mounted() {
// load the `auth0-js` here
...
}
In my instance (with Firebase Auth) this was the solution:
In the Default Layout component:
const app = import("firebase/app");
const auth = import("firebase/auth");
const database = import("firebase/firestore");
const storage = import("firebase/storage");
Promise.all([app, auth, database, storage]).then(values => {
// now we can access the loaded libraries 😍!
});
}

Importing npm packages in Nativescript Playground

I'm trying to learn nativescript-vue where I'm using the Nativescript's Playground to tryout my sample codes. I'm trying to use nativescript-localstorage package so that I can store some of the information into local storage:
Whenever I'm trying to save project it is giving use compilation error
and following is the error:
An error occurred while transpiling nativescript-localstorage/localstorage.js.
unknown: We found a path that isn't a NodePath instance. Possiblly due to bad serialisation.
I followed the tutorials and added the package as it was instructed my code looks like:
import Vue from 'nativescript-vue';
import Vuex from 'vuex';
import localStorage from 'nativescript-localstorage';
import userStore from './user-store';
//For local storage of vuex tools
const NSVuexPersistent = store => {
// Init hook.
let storageStr = localStorage.getItem('ns-vuex-persistent');
if (storageStr) {
store.replaceState(JSON.parse(storageStr))
}
store.subscribe((mutation, state) => {
// Subscribe hook.
localStorage.setItem('ns-vuex-persistent', JSON.stringify(state));
})
};
Vue.use(Vuex);
const debug = process.env.NODE_ENV !== 'production';
export default new Vuex.Store({
modules: {
userStore
},
strict: debug,
plugins: [NSVuexPersistent]
})
Since the project is not getting saved so I've not shared the link. Help me out with it. Thanks.
nativescript-vue is packaged within the Preview APK, so it can be imported as
import Vue from 'nativescript-vue'
But nativescript-localstorage is something you have installed in your project, so while at Playground you should use relative path to import the module, something like
import * as localStorage from "../nativescript-localstorage"
// Or
const localStorage = require("../nativescript-localstorage");
You can use import name from "package" only when the package has marked something as default in its exports, the syntax is commonly used in ES6 & Vue plugins. nativescript-localstorage has not exported anything as default.

Categories