I decided to rewrite my application from spa vue to nuxt but i faced a problem in spa, in vue i could just import store and used it but in nuxt i cant do the same, i am getting undefined object every time
in vue spa i had folder with some api services and with main api.js which include this code
import axios from 'axios'
import store from '@/store/index'
export default () => {
return axios.create({
baseURL: `http://myip.com/`,
headers: {
Authorization: `Bearer ${store.state.token}`
}
})
}
then in other js files i just import this api.js file and use something like this
import Api from '@/services/Api'
export default {
register (credetinals){
return Api().post('register', credetinals)
},
login (credetinals){
return Api().post('login', credetinals)
}
}
so i had 10 js files services where i include api.js and then in files *.vue i just import this service how can i do the same in nuxt ?
If you add your state under the /store/index.js it will automatically append in the application, you dont need to import it in your file.
What you can do is try to check the state using:
window.$nuxt.$store.state
Also dont forget to add a condition process.browser since you want to check it in browser.
Here is what I did in my api.js file for your reference:
// Libraries
import axios from 'axios';
// API Instance
export const instance = axios.create({
baseURL: 'http://myip.com/',
headers: {},
validateStatus: status => {
return status;
},
});
// API Interceptors
instance.interceptors.request.use(config => {
if (process.browser) {
const userToken = window.$nuxt.$store.getters.getUserToken;
// Set Authorization token
if (userToken) {
config.headers['Authorization'] = `Bearer ${userToken}`;
}
}
return config;
}, function (error) {
return Promise.reject(error);
});