My app init after some async changes (my main.js):
(async function () {
try {
let response = await fetch('/config.json');
let config = await response.json();
window.appConfig = config;
appInit();
} catch (error) {
alert('appConfig not found!')
window.stop();
}
})();
and inside appInit() i use
new Vue({
el: '#app',
render: h => h(App),
router,
i18n,
store
})
But i have some texts inside .js file and now i use like this:
export default { super_name: 'Super name' }
My question: how can i use inside .js file dynamic $i18n texts? I can't export new Vue, because it is inside function appInit()
I tried almost everything
Related
I am trying to display my date from GraphCMS in my blog application. I receive this error when I go to my single post link (http://localhost:3000/posts/union-types-and-sortable-relations)
"
page in load functions has been replaced by url and params
Error: page in load functions has been replaced by url and params
"
Here is my code
<script context='module'>
export const load = async ({fetch, page: {params}}) => {
const {slug} = params
const res = await fetch(`/posts/${slug}.json`)
if(res.ok) {
const {post} = await res.json()
return {
props: {post},
}
}
}
</script>
<script>
export let post
</script>
<svelte:head>
<title>Emrah's Blog | Welcome</title>
</svelte:head>
<pre>{JSON.stringify(post, null, 2)}</pre>
Can you please help. Thanks
Try using params instead of page: params, though the latter still works in Sveltekit 278 (which I'm using).
Besides, I'm curious to know what makes you prefer this method to querying GraphCMS for your single post. I do it like this:
import {client} from '$lib/js/graphql-client'
import {projectQuery} from '$lib/js/graphql-queries'
export const load = async ({ params }) => {
const {slug} = params
const variables = {slug}
const {project} = await client.request(projectQuery, variables)
return {
props: {
project
}
}
}
Yes, this has been changed a while ago, now the different parts of what used to be page are passed directly into the load function:
export async function load({ fetch, page }) {
const { params, url } = page
}
export async function load({ fetch, params, url }) {
}
Something else to consider is that now there are page endpoints, if your file is [slug].svelte you can make a file [slug].js and add the following:
export async function get({ params }) {
const { slug } = params;
const post = {}; // add the code to fetch from GraphCMS here
return {
status: 200,
body: {
post
}
}
}
With this you can remove the load function and make your code simpler (especially because you technically already have all this code in your /posts/[slug].json.js file.
<script context='module'>
export async function load({ fetch, params}){
let id = params.users
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
const user = await response.json()
if(response.ok){
return {props:{user}}
}
return {
status: response.status,
error : new Error(" sorry no user found")
}
}
export let user
I'm using Svelte and Protobuf generated clients.
In ./generated/index.ts I'm using this code:
import type { PlayerServiceClient } from './proto/player.client';
const transport = new GrpcWebFetchTransport({ baseUrl: 'http://localhost:3000/api' });
let playerService: PlayerServiceClient;
export const player = async (): Promise<PlayerServiceClient> =>
playerService ||
((playerService = new (await import('./player.client')).PlayerServiceClient(transport)),
playerService);
which is why I'm using the below code that I don't like because is too verbose, DRY and long:
import { player } from "../generated";
let players: Player[];
(async () => {
const playerService = await player();
const { response } = await playerService.queryPlayers({ playerId: "1" });
if (response) {
players = response.players;
}
})();
QUESTION:
Is there a way to still have lazy import() but without the verbose double await in each component?
I would like to have this code instead:
import { player } from "../generated";
let players: Player[];
(async () => {
players = await player.queryPlayers({ playerId: "1" });
})();
Additional context:
I have many different types (and therefore services) (hundreds) and many different navigation routes: this is why I need lazy load.
I'm building a fairly large SPA using Vue (and Laravel for RESTful API). I'm having a hard time finding resources about this online - what's a good practice to organise the code that communicates with the server?
Currently I have src/api.js file, which uses axios and defines some base methods as well as specific API endpoints (truncated):
import axios from 'axios';
axios.defaults.baseURL = process.env.API_URL;
const get = async (url, params = {}) => (await axios.get(url, { params }));
const post = async (url, data = {}) => (await axios.post(url, data));
export const login = (data) => post('users/login', data);
And then in my component, I can do
...
<script>
import { login } from '#/api';
...
methods: {
login() {
login({username: this.username, password: this.password})
.then() // set state
.catch() // show errors
}
}
</script>
Is this a good practice? Should I split up my endpoints into multiple files (e.g. auth, users, documents etc.)? Is there a better design for this sort of thing, especially when it comes to repetition (e.g. error handling, showing loading bars etc.)?
Thanks!
If you're just using Vue and expect to be fetching the same data from the same component every time, it's generally idiomatic to retrieve the data and assign it using the component's mounted lifecycle hook, like so:
<template>
<h1 v-if="name">Hello, {{name}}!</h1>
</template>
<script>
export default {
data() {
return {
name: '',
}
},
mounted() {
axios.get('https://example.com/api')
.then(res => {
this.name = res.data.name;
})
.catch(err =>
// handle error
);
},
};
</script>
If you're going to be using Vuex as mentioned in one of your comments, you'll want to put your API call into the store's actions property.
You'll end up with a Vuex store that looks something like this:
const store = new Vuex.Store({
state: {
exampleData: {},
},
mutations: {
setExampleData(state, data) {
state.exampleData = data;
},
},
actions: {
async getExampleData() {
commit(
'setExampleData',
await axios.get('https://www.example.com/api')
.then(res => res.data)
.catch(err => {
// handle error
});
);
},
}
});
Of course, breaking out your state, actions, and mutations into modules as your app grows is good practice, too!
If you use Vue CLI it will setup a basic project structure. With a HelloWorld component. You will want to break your vue app into components. Each component should have a defined role that ideally you could then unit test.
For example lets say you want to show list of products then you should create a product list component.
<Products :list="products" />
In your app you would do something like
data() {
return {
prodcuts: []
}
},
mounted() {
axios.get('/api/products').then(res => {
this.products = res.data
})
}
Whenever you see something that "is a block of something" make a component out of it, create props and methods and then on the mounted hook consume the api and populate the component.
The main use of this is to store a new token that will be refreshed on every request automatically in the Vuex store.
However, I don't seem to understand how I can import the store, so that I can store.dispatch('STORE_TOKEN') from the interceptor.
Note that my app is SSR and that the Vue APP itself is being created by the factory method createApp().
How can I import the store and make it work?
app.js
export function createApp () {
// create store and router instances
const store = createStore()
const router = createRouter()
// sync the router with the vuex store.
// this registers `store.state.route`
sync(store, router)
// create the app instance.
// here we inject the router, store and ssr context to all child components,
// making them available everywhere as `this.$router` and `this.$store`.
const app = new Vue({
router,
store,
render: h => h(App)
})
// expose the app, the router and the store.
// note we are not mounting the app here, since bootstrapping will be
// different depending on whether we are in a browser or on the server.
return { app, router, store }
}
axios-instance.js
import axios from 'axios';
var instance = axios.create();
instance.defaults.baseURL = 'http://localhost:8000';
instance.interceptors.response.use((response) => {
console.log("interceptop", response);
console.log(this.$store);
return response;
});
export default instance;
api.js
import axios from 'axios'
export function loginUser() {
return new Promise((resolve, reject) => {
axios({
'method': 'post',
'url': 'http://localhost:8000/auth/login',
'data': {
'email': 'user1#example.com',
'password': '1234'
}
}).then((response) => {
console.log(response);
return response.data;
}).then(
(result) => {
console.log("Response", result);
resolve(result)
},
(error) => {
reject(error)
}
)
})
}
Before I was getting movie detail from the component's script. The function first check whether the movie ID of the store is same as of the route's param movie ID. If its same then don't get the movie from the server API, or else get the movie from the server API.
It was working fine. But now I am trying to get the movie details from the store's mutation. However I am getting error
Uncaught TypeError: Cannot read property '$route' of undefined
How to use vue-router ($route) to access the params and vue-resource ($http) to get from the server API in vuex store?
store.js:
export default new Vuex.Store({
state: {
movieDetail: {},
},
mutations: {
checkMovieStore(state) {
const routerMovieId = this.$route.params.movieId;
const storeMovieId = state.movieDetail.movie_id;
if (routerMovieId != storeMovieId) {
let url = "http://dev.site.com/api/movies/movie-list/" + routerMovieId + "/";
this.$http.get(url)
.then((response) => {
state.movieDetail = response.data;
})
.catch((response) => {
console.log(response)
});
}
},
},
});
component script:
export default {
computed: {
movie() {
return this.$store.state.movieDetail;
}
},
created: function () {
this.$store.commit('checkMovieStore');
},
}
To use $http or $router in your vuex store, you would need to use the main vue instance. Although I don't recommend using this, I'll add what I recommend after answering the actual question.
In your main.js or wherever you are creating your vue instance like:
new Vue({
el: '#app',
router,
store,
template: '<App><App/>',
components: {
App
}
})
or something similar, you might also have added the vue-router and vue-resource plugins too.
Doing a slight modification to this:
export default new Vue({
el: '#app',
router,
store,
template: '<App><App/>',
components: {
App
}
})
I can now import it in vuex stores like so:
//vuex store:
import YourVueInstance from 'path/to/main'
checkMovieStore(state) {
const routerMovieId = YourVueInstance.$route.params.movieId;
const storeMovieId = state.movieDetail.movie_id;
if (routerMovieId != storeMovieId) {
let url = "http://dev.site.com/api/movies/movie-list/" + routerMovieId + "/";
YourVueInstance.$http.get(url)
.then((response) => {
state.movieDetail = response.data;
})
.catch((response) => {
console.log(response)
});
}
}
and as the answer by Austio goes, this method should be an action as mutations are not designed to handle async.
Now coming to the recommended way of doing it.
Your component can access the route params and provide it to the action.
methods: {
...mapActions({
doSomethingPls: ACTION_NAME
}),
getMyData () {
this.doSomethingPls({id: this.$route.params})
}
}
The action then makes the call through an abstracted API service file (read plugins)
[ACTION_NAME]: ({commit}, payload) {
serviceWhichMakesApiCalls.someMethod(method='GET', payload)
.then(data => {
// Do something with data
})
.catch(err => {
// handle the errors
})
}
Your actions do some async job and provide the result to a mutation .
serviceWhichMakesApiCalls.someMethod(method='GET', payload)
.then(data => {
// Do something with data
commit(SOME_MUTATION, data)
})
.catch(err => {
// handle the errors
})
Mutations should be the only ones to modify your state.
[SOME_MUTATION]: (state, payload) {
state[yourProperty] = payload
}
Example
A file which contains a list of endpoints, you might need it if you have different stages of deployment which have different api endpoints like: test, staging, production, etc.
export const ENDPOINTS = {
TEST: {
URL: 'https://jsonplaceholder.typicode.com/posts/1',
METHOD: 'get'
}
}
And the main file which implements Vue.http as a service:
import Vue from 'vue'
import { ENDPOINTS } from './endpoints/'
import { queryAdder } from './endpoints/helper'
/**
* - ENDPOINTS is an object containing api endpoints for different stages.
* - Use the ENDPOINTS.<NAME>.URL : to get the url for making the requests.
* - Use the ENDPOINTS.<NAME>.METHOD : to get the method for making the requests.
* - A promise is returned BUT all the required processing must happen here,
* the calling component must directly be able to use the 'error' or 'response'.
*/
function transformRequest (ENDPOINT, query, data) {
return (ENDPOINT.METHOD === 'get')
? Vue.http[ENDPOINT.METHOD](queryAdder(ENDPOINT.URL, query))
: Vue.http[ENDPOINT.METHOD](queryAdder(ENDPOINT.URL, query), data)
}
function callEndpoint (ENDPOINT, data = null, query = null) {
return new Promise((resolve, reject) => {
transformRequest(ENDPOINT, query, data)
.then(response => { return response.json() })
.then(data => { resolve(data) })
.catch(error => { reject(error) })
})
}
export const APIService = {
test () { return callEndpoint(ENDPOINTS.TEST) },
login (data) { return callEndpoint(ENDPOINTS.LOGIN, data) }
}
The queryAdder in case it is important, I was using this to add params to the url.
export function queryAdder (url, params) {
if (params && typeof params === 'object' && !Array.isArray(params)) {
let keys = Object.keys(params)
if (keys.length > 0) {
url += `${url}?`
for (let [key, i] in keys) {
if (keys.length - 1 !== i) {
url += `${url}${key}=${params[key]}&`
} else {
url += `${url}${key}=${params[key]}`
}
}
}
}
return url
}
So a few things, the $store and $route are properties of the Vue instance, which is why accessing them inside of Vuex instance is not working. Also, mutations are synchonous what you need are actions
Mutations => A function that given state and some arguments mutates the state
Action => Do async things like http calls and then commit results to a mutation
So create an action that dispatches the http. Keep in mind this is pseudocode.
//action in store
checkMovieStore(store, id) {
return $http(id)
.then(response => store.commit({ type: 'movieUpdate', payload: response })
}
//mutation in store
movieUpdate(state, payload) {
//actually set the state here
Vue.set(state.payload, payload)
}
// created function in component
created: function () {
return this.$store.dispatch('checkMovieStore', this.$route.params.id);
},
Now your created function dispatches the checkMovieStore action with the id, which does the http call, once that is complete it updates the store with the value.
In your vuex store:
import Vue from 'vue'
Vue.http.post('url',{})
Not like in normal vue components:
this.$http.post(...)
I highly recommend importing axios on the vuex module (store and submodules), and using it for your http requests
To access the vue instance in the store use this._vm.
But as Amresh advised do not use things like $router in vuex