Nuxt Fetch Doesn't Update on First Load - vue.js

I'm having the following issue and hope someone could help me on it:
Fetch is not working on the first load (nor on reloads). It only works when on the client-side (when I move between routes).
I've read that watchQuery could help but didn't understand why and how to use it.
<script>
export default {
async fetch() {
const userId = await this.$nuxt.context.store.state.auth.authUser.userId
await this.$store.dispatch('case/fetchMyCases', userId.uid)
await this.$store.dispatch('case/fetchMyPendingCases', userId.uid)
...
It doesn't work even if I import and use firebase/auth directly.
<script>
import * as firebase from 'firebase/app'
import 'firebase/auth'
export default {
async fetch() {
const userId = await firebase.auth().currentUser
await this.$store.dispatch('case/fetchMyCases', userId.uid)
await this.$store.dispatch('case/fetchMyPendingCases', userId.uid)
...
Does anyone have any tips for it? I'd really appreciate it.
Thanks!

After literally 3 days searching/testing, I finally found out why I was having this issue.
The problem was that I simply put async/await for fetch but didn't put async/await for the actions itself. Therefore, my getter (in computed) was getting the store state before the dispatches have been finished.
Thanks, everyone!

Warning: You don't have access of the component instance through this inside fetch because it is called before initiating the component (server-side).
async fetch({ store }) {
await store.dispatch('case/fetchMyCases')
await store.dispatch('case/fetchMyPendingCases')
}
If you need parameter:
async fetch({ store, params }) {
await store.dispatch('case/fetchMyCases', params.uid)
await store.dispatch('case/fetchMyPendingCases', params.uid)
}
I gave an example of id. The name of the parameter depends on the name of your page.
_id => params.id
_uid => params.uid
_slug => params.slug
...

Yes, You must put async/await on actions.
async automatically returns a promise
If you don't need the value, in this case, don't anything return.
export const Actions = {
async fetchUsers() {
// It will return automatically promise
await this.$axios.get('API')
}
}
// If you need returne value
// First way
export const Actions = {
async fetchUsers() {
// It will return promise and value
return await this.$axios.get('API')
}
}
// Second way
export const Actions = {
async fetchUsers() {
// It will return promise and value
const response = await this.$axios.get('API')
return response;
}
}

Related

NuxtJS dispatch is not loading data

I've been struggling for 5 hours with the following issue.
I have a service file where I have API calls using Axios. In the store, I have an action that uses the service to pull a list of schools, then I commit the data to the mutations. If I console log the data on the mutation object, it works correctly and shows the data. However, when I call dispatch from the component inside the onMounted hook, I get an empty object. Any help is greatly appreciated. (see the code below)
store/schools.js
export const state = () => ({
mySchools: []
});
export const mutations = {
getSchools(state, data) {
state.schools = data;
console.log(state.schools); // works;
}
};
export const actions = {
async getMySchools({ commit }) {
await this.$getSchools().then(response => {
commit("getSchools", response.data);
});
}
};
portal/dashboard.vue
import {onMounted, ref, useStore} from "#nuxtjs/composition-api";
export default {
layout: 'portal',
setup() {
const store = useStore();
const schools = ref([]);
onMounted(async() => {
await store.dispatch('schools/getMySchools'); // is not pulling data
schools.value = store.state.schools.mySchools;
console.log(schools); // empty
});
return {
schools
}
}
};
Thank you
You shouldn't use await with then
try this
async getMySchools({ commit }) {
const response = await this.$getSchools();
commit("getSchools", response.data);
}
I'm assuming that your this.$getSchools() actually works since I'm not sure what that is and it's not part of the code

Nuxt await async + vuex

Im using nuxt and vuex. In vuex im getting data:
actions: {
get_posts(ctx) {
axios.get("http://vengdef.com/wp-json/wp/v2/posts").then(post => {
let posts = post.data;
if (!posts.length) return;
let medias_list = "";
posts.forEach(md => {
medias_list += md.featured_media + ","
});
medias_list = medias_list.slice(0, -1);
let author_list = "";
posts.forEach(md => {
author_list += md.author + ","
});
author_list = author_list.slice(0, -1);
axios.all([
axios.get("http://vengdef.com/wp-json/wp/v2/media?include=" + medias_list),
axios.get("http://vengdef.com/wp-json/wp/v2/users?include=" + author_list),
axios.get("http://vengdef.com/wp-json/wp/v2/categories"),
]).then(axios.spread((medias, authors, categories) => {
ctx.commit("set_postlist", {medias, authors, categories} );
})).catch((err) => {
console.log(err)
});
})
}
},
In vuex state i have dynamic postlist from exaple below.
How i can use it in Nuxt?
In nuxt i know async fetch and asyncData.
async fetch () {
this.$store.dispatch("posts/get_posts");
}
Thats not working.
How i can say to nuxt, wait loading page, before vuex actions loading all data?
As you already mentioned there are:
fetch hook
asyncData
And differences are well described here
The reason why your code is not working might be in your store action.
It should return a promise, try to add return before axios get method ->
get_posts(ctx) {
return axios.get(...
// ...
And then, on your page:
async fetch () {
await this.$store.dispatch("posts/get_posts");
}
Also, in comment above you're saying that you dont want to commit data in store:
...load page only after vuex, i dont need to pass data in vuex
But you do it with this line:
ctx.commit("set_postlist", {medias, authors, categories} );
if you dont want to keep data in store, just replace line above with:
return Promise.resolve({ medias, authors, categories })
and get it on your page:
async fetch () {
this.posts = await this.$store.dispatch("posts/get_posts");
// now you can use posts in template
}
Misread the actual question, hence the update
With Nuxt, you can either use asyncData(), the syntax will change a bit tho and the render will be totally blocked until all the calls are done.
Or use a combo of fetch() and some skeletons to make a smooth transition (aka not blocking the render), or a loader with the $fetchState.pending helper.
More info can be found here: https://nuxtjs.org/docs/2.x/features/data-fetching#the-fetch-hook
Older (irrelevant) answer
If you want to pass a param to your Vuex action, you can call it like this
async fetch () {
await this.$store.dispatch('posts/get_posts', variableHere)
}
In Vuex, access it like
get_posts(ctx, variableHere) {
That you can then use down below.
PS: try to use async/await everywhere.
PS2: also, you can destructure the context directly with something like this
get_posts({ commit }, variableHere) {
...
commit('set_postlist', {medias, authors, categories})
}

#react-native-async-storage/async-storage getItem is giving value as false

I am trying to access react-native Async storage in a different file from where it has been set. In the same file where it is being set , i am able to get the value. but in the different file i am getting "false" as the value.
Any help would be greatly be appreciated.
import AsyncStorage from '#react-native-async-storage/async-storage';
const getData = async () => {
console.log("fetching data from asyncstorage")
try {
const value = await AsyncStorage.getItem('userToken'); << retuning false
if(value !== null) {
console.log(value);
token.token=value;
}
} catch(e) {
console.log(e);
}
}
const callfunction=()=>{
getData();
}
This is how i was able to make it work,If somebody got a better solution please do post here,
As operation with AsyncStorage are happening in async manner, meaning the main thread will not wait for the function call to be coompleted, i found it best to call the function way before i needed it and keep it stored.
In order to acheive this i used a react hook "useEffect" this is similar to springboot alternative #PostConstruct, meaning "useEffect" will be called the moment you are navigate to the page. So the code looks something like this.
import AsyncStorage from '#react-native-async-storage/async-storage';
import React,{useEffect} from 'react';
const [token, setToken] = React.useState({
token: "",
});
const getData = () => {
console.log("fetching data from asyncstorage")
AsyncStorage.getItem('userToken').then((value) => {
console.log("token : "+ value);
token.token=value;
}).done();
}
useEffect(() => {
if(token.token=="")
{
getData();
}
});
If someone finds any good blog or video supporting this do post it here, also if my explanation, is deviating from technical aspect please help me understand it better.

Vuex, best practice with a global errors and notifications handling

here is what i do, and i'am not realy sure its correct :
//store
async addUser({commit}) {
try {
const {data} = await apiService.addUser()
commit('SET_USER', data)
commit('SET_NOTIFICATION', {type:'success', message: 'user successfuly created'})
} catch (error) {
commit('SET_NOTIFICATION', {type:'error', message:error})
}
}
SET_USER(state, user) {
state.users.push(user)
}
//my component:
async addUser() {
this.isLoading = true
await this.$store.dispatch('updatePatient', this.form)
this.isLoading = false
}
is it legit ?
sometimes i think i would need more logic inside my component depending on the succes or rejected api request. Should i put all the logic in my actions ? like i do at the moment ?
Maybe should I add a status state for each actions, for example :
state {
users: []
postUserSuccess: null
postUserError: false
updateUserSuccess: null
updateUserError: false
// ...
}
and do what i want in the component with a computed property mapped to the store ?
What do you think ?
I don't know if it's a best practice but I let the components the exception handling. That method has its pros (you don't have to pollute the state with error management) and cons (you have to repeat the error management code for every action call).
All service calls will be made in actions
The state will only be set in mutations.
All service calls will return a promise with a resolve(data to load in the state) and a reject(message errors to present).
There will be an interceptor to reject the response in case there's a custom error (here you can put if the response has an error prop reject the response and send as an error the error prop, now you don't have to deconstruct the response in the action).
I'm going to give you a simplified example (I use axios, you can learn how to do it with the library that you use).
Actions in Vuex are asynchronous. So you don't need to try/catch them.
ApiService - Add User
const addUser = () => {
return new Promise((resolve, reject) => {
axios
.post(url, user)
.then(response => resolve(response.data))
.catch(error => reject(error));
});
};
store
async addUser({commit}) {
const data = await apiService.addUser();
commit('SET_USER', data);
return data;
}
if the promise in apiService.addUser is resolved the commit is going to be made if is rejected axios will return the promise and you can catch the error in the component that calls the action.
Component
async addUser() {
this.isLoading = true;
try {
await this.$store.dispatch('updatePatient', this.form);
} catch (error) {
// here goes the code to display the error or do x if there is an error,
// sometimes I store an errors array in the data of the component other times I do x logic
}
this.isLoading = false;
}
State
Your state will be cleaner now that you don't need to store those errors there.
state {
users: []
}

Get item from AsyncStorage in React Native

I have a list of companies in React Native.
When I click on one of those companies I get the url of the API that is used for selected company. Then I store it to AsyncStorage and then I show the login screen. The function is as follows:
selectCompany(data_url, e) {
AsyncStorage.setItem("data_url", JSON.stringify(data_url), () => this.props.login());
}
Then on login page if I click on sign in button I go to the onLogin function, the function is as follows:
onLogin: function() {
fetch(data.url + '/manager/api/v1/obtain-auth-token/', })
.then(function(body) {
return body.json();
}).then(function(json) {
.....
}).catch(function() {
....
});
},
And data.url comes from data.js file, and I try to get url from the data.js file as follows:
let data_url = AsyncStorage.getItem("data_url").then(json => JSON.parse(json));
module.exports = {
url: data_url,
.....
}
But it doesn't work. Any advice?
AsyncStorage is async, therefore data_url will not be defined until it's retrieved what its looking for, you would need to move the fetch into the promise thats returned from the get so it will run it once it's done getting the data. This might be one way you tackle it:
const data_url = () => AsyncStorage.getItem("data_url"); //change this into a function
module.exports = {
url: data_url,
.....
}
now inside your component...
onLogin: function() {
data.url().then((url) => {
fetch(JSON.parse(url) + '/manager/api/v1/obtain-auth-token/', })
.then(function(body) {
return body.json();
}).then(function(json) {
.....
}).catch(function() {
....
});
});
},
AsyncStorage.getItem is a promise and needs to await for response rather than accessing direct and the function calling it should be defined as async. Here is an example to retrieve from AsyncStorage..
export async function getAccessKey(){
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
return accessToken;
}