How to get access beforeCreate() global app in Nuxt? - vue.js

I want to get access beforeCreate() app cycle method in Nuxt and load data from localStorage to Vuex store, how can I do that?

You could use Nuxt middleware to achieve a beforeCreate() effect.
// /nuxtproject/middleware/store_check.js
export default function ({ store }) {
store.dispatch('stateModule/stateAction')
}
// /nuxtproject/pages/index.vue
export default {
components: {
Header
},
middleware: 'store_check',
}
As for loading from localStorage, you can use it with the middleware solution above provided Nuxt is running in SPA mode - because localStorage isn't natively available on Nuxt Universa/SSR mode.
Had this same problem after spending some hours and this other stackoverflow answer explains why (with alternatives)
https://stackoverflow.com/a/57512785/842834

Related

Nuxtjs store undefined in middleware on refresh

I'm using nuxt js for my web app, I need to keep the store when I refresh the page, even in middleware or the page itself.
I'm using vuex-persistedstate;
import createPersistedState from "vuex-persistedstate";
export default ({ store }) => {
if (process.client) {
window.onNuxtReady(() => {
createPersistedState({})(store);
});
}
};
One of the solutions that I tried is to use cookies in the store, but my data is very huge and I need it in the local storage.
I think it's something related to SSR or server middleware, I tried a lot to figure out how to solve it, but nth is working.
It is impossible because we are not able to access localStorage when component is rendering on the server side. You should either turn off ssr to use localStorage or try to reduce the size of your data to put it in cookies.

How we can set default route in NUXTJS

How we can customize NUXT routing. Currently, I am working with the default NUXT page routing mechanism. I want to point example.vue as the default landing page instead of index.vue. I also need to add authentication on these routing. unfortunately, NUXT document didn't help me well.
Check to middleware Property on Nuxt
You can write a middleware and call it in your index.vue as:
middleware: {
'redirect-to-example'
}
middleware/redirect-to-example.js
export default function ({ store, redirect }) {
// If the user is not authenticated
if (!store.state.authenticated) {
return redirect(301, '/example');
}
}
You find useful informations about The Context to play well with Nuxt
To change the landing page you can use the following pages/index.vue:
<template>
</template>
<script>
export default {
created() {
this.$router.push('/example')
},
}
</script>
when the user navigates to https://localhost:3000 the route /projects will be pushed and the url will change to https://localhost:3000/example, this can be seen as an internal "redirect".

Make Vue data globally available and accessible for all components

In have a simple Vue cli app with some pages.
In Users.vue I fetch the data from an API with axios:
<script>
import axios from 'axios'
export default {
data() {
return {
users: []
}
},
mounted () {
axios
.get('https://api.github.com/users')
.then(response => (this.users = response.data))
}
}
</script>
This works fine. I can access the properties.
But how do I add axios and the mounted hook globally e.g. to App.vue and be able to access the data from the json in every component?
In order to use the data from everywhere in your application. you should save it in store. using vuex. https://vuex.vuejs.org/
another way could be fine too, in case you need the data just in user's children. you can simply pass the data by using props https://v2.vuejs.org/v2/guide/components-props.html

Nuxt - define a const once and which can use across all pages

I'm trying to implement Shopify JS SDK in Nuxt
So this is what I did, a plugin
// plugins/shopify.js
import Vue from 'vue'
import 'isomorphic-fetch'
import Shopify from 'shopify-buy'
export default ({ app }, inject) => {
app.shopify = Shopify.buildClient({
domain: 'aaa.myshopify.com',
storefrontAccessToken: 'aaa'
});
}
nuxt config
//nuxt.config.js
plugins : [{ src : '~/plugins/shopify', ssr: false}]
vendor : ['shopify-buy']
index
asyncData ({ app }) {
return app.shopify.product.fetchAll().then((products) => {
// Do something with the products
console.log(products);
return { products : products }
});
}
The result is
TypeError Cannot read property 'product' of undefined
But it works if I removed the asyncData, refresh my page, and add the code back without refreshing.
I believe this has something to do with the lifecycle.
Can anyone please tell me if I'm doing it the right way, or there's other proper way to define such const which can be use across pages, components etc
And if this is the right way, what I did wrong?
Thanks in advance.
My reference are Nuxt guides as well as examples.
I tried google around but can't locate what I need, or maybe I just didn't get the right keywords.
FROM DOCUMENTATION
Nuxt.js lets you create environment variables that will be shared for
the client and server-side.
To do this, you can use the env property:
nuxt.config.js:
module.exports = {
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
}
}
Then to access it from anywhere, just use it like so:
process.env.baseEnv
For example, in an axios plugin:
import axios from 'axios'
export default axios.create({
baseURL: process.env.baseUrl
})

how to make a component to get async data and to render server side?

We know that only router component may request asyncData in a ssr environment. i have one main component(not router component), i need some async data to render server side. because it is not router component, so i can't use asyncData for server side rendering.
so i have used created hook for calling async api, but component hook is synchronous and don't wait for promise. what to do for getting async data on server side?
App.vue - Main Component
export default {
components: {
footer: Footer,
header: Header,
selector: selector
},
beforeMount() {
// need preload metadata here
},
created () {
// it return preload metadata as response.
return this.$store.dispatch('GET_PRELOAD_META_DATA');
}
}
Action.js
GET_PRELOAD_META_DATA: ({ commit }) => {
return axios.get("api/preload").then(({ data }) => {
commit('SET_PRELOAD_DATA', data);
});
},
As of Vue 2.6, there is a new SSR feature that may accomplish what you’re trying to do. ServerPrefetch is now a hook that can resolve promises to get async data and can interact with a global store.
Check out more in their documentation. https://ssr.vuejs.org/api/#serverprefetch
(I know this an old post, but I stumbled upon it while googling and thought I might be able to help someone else googling too)