Setting Data from Axios GET - vue.js

I know there are similar questions to this but i've tried the solutions and nothing seems to be working
My code takes user input, makes a axios get request based off that input and aims to assign the data to the array staffs[]
export default {
data(){
return{
staffs: [],
userInput:'',
errors: '',
}
},
created:function(){
bus.$on('search-data',inputData =>{
axios.get('http://localhost:4000/stafftest?username='+inputData)
.then(response => {
console.log(JSON.stringify(response.data))
this.staffs = response.data.data
})
.catch(error =>{
console.log(error)
})
})
},
}
Similar issue to what everyone else has asked, the axios request is made successfully but it won't assign data to the array
Here's a combo of things i tried:
https://codeshare.io/ammpP4 https://codeshare.io/G798xD
https://codeshare.io/2Ewk1P https://codeshare.io/GqDPPk
https://codeshare.io/GLbwwp
tried changing it to function(response) etc and having a var self=this, yet none of it seems to work
I even set up another test page which queries a pokemon API and the data assigmemt went smoothly, which leaves me confused as to why in this case on this certain page it won't work
Appreciate any ideas to get this fixed
Thanks

Related

How to hide code from client side in vue/nuxt, using Server Side Rendering?

I am trying to do some processing on the server side, which I do not want to be viewable on the client side.
I have successfully tried using either fetch or asyncData to populate the state, but I do not want the process followed to be available on the browser.
For example:
<template>
// ...
</template>
<script>
import ...
export default {
layout: 'layout1',
name: 'Name',
components: { ... },
data: () => ({ ... }),
computed: { ... },
async asyncData({ store }) {
const news = await axios.get(
'https://newsurl.xml'
).then(feed =>
// parse the feed and do some very secret stuff with it
// including sha256 with a salt encryption
)
store.commit('news/ASSIGN_NEWS', news)
}
}
</script>
I want the code in asyncData (or in fetch) not to be visible on the client side.
Any suggestion will be appreciated.
There are several questions like this one already, one of which I've answered here and here.
The TLDR being that if you want to make something on server only, you probably don't even want it part of a .vue file from the beginning. Using a backend proxy could also be useful (as stated above), especially if you could benefit from caching or reduce bandwidth overall.
You can use onServerPrefetch hook.
onServerPrefetch(async () => {
const news = await axios.get(
'https://newsurl.xml'
).then(feed =>
// parse the feed and do some very secret stuff with it
// including sha256 with a salt encryption
)
this.$store.commit('news/ASSIGN_NEWS', news)
})

How do i retrive the city name from opengatedata.com

'''if (await permission()) {
Geolocation.getCurrentPosition(
async position => {
await fetch(
`https://api.opencagedata.com/geocode/v1/json?q=${position.coords.latitude}+${position.coords.longitude}&key=apikey&pretty=1`,
).then(result => {
console.log(result.data);
});
},
error => {
console.log(error.code, error.message);
},
);
}'''
How do i retrive the returned location from the response sent to me
The things it sends me seems like gibrish and have no clue what to do and i am building the app in react-native using tsx
All you need to do is console the response to make sure that you are receiving your response as expected after that you've multiple choices to extract the required data e.g. Destructuring or looping through the response (quite expensive + time taking) or you can use the filter method, in a nutshell, there are tons of way to get your required data from the response and it's just a matter of your taste(like whichever you prefer)

How to use Nuxt $auth inside an axios plugin (How to add Token to all axios requests)

Im looking to use $auth inside my Nuxt project, specially inside an axios plugin.
Here is my code:
plugins/api.js
export default function ({ $axios }, inject) {
const api = $axios.create({
headers: {
common: {
Accept: 'text/plain, */*',
},
},
})
// Set baseURL to something different
api.setBaseURL('http://localhost:4100/')
// Inject to context as $api
inject('api', api)
}
Now the problem comes when I try to use $auth from #nuxtjs/auth-next package.
As stated in the docs:
This module globally injects $auth instance, meaning that you can
access it anywhere using this.$auth. For plugins, asyncData, fetch,
nuxtServerInit and Middleware, you can access it from context.$auth.
I tried the following:
This results in $auth being undefined
export default function ({ $axios, $auth }, inject) {
This one was near
export default function ({ $axios, app }, inject) {
console.log(app) //This one logs $auth in the object logged
console.log(app.$auth) // I don't understand why but this one returns undefined
My main goal here is to make use of this.$auth.strategy.token.get()and pass it (if the token exists of course) to the headers of every request made using this.$api
I have been looking for similar questions and answers but none has helped me to solve this, I could just add the token every time I write this.$api but that would increase the code unnecessarily.
Thanks in advance to all the people for your time and help.
EDIT:
Okay, now I made a test. and the next code is actually logging the $auth object correctly, it seems some time is needed to make it work but now Im afraid that using setTimeout could cause an error because I can't know exactly how much time is needed for $auth to be available.
export default function ({ $axios, app }, inject) {
setTimeout(() => {
console.log('After timeout', app.$auth)
}, 50)
EDIT 2:
So now I have made more tests, and using 0 milliseconds instead of 50 works too, so I will use setTimeout with 0 milliseconds for now, I hope anyone find a better solution or explain why $auth is not available before using setTimeout so I can decide what to do with my code.
EDIT 3:
After trying to wrap all my previous code inside setTimeout I noticed that the code fails, so that isn't a solution.
I have found a solution so I will post it so that every person that could have the same problem in the future can solve it.
It turns out that I could easily solve it using interceptors.
export default function ({ $axios, app }, inject) {
// At this point app.$auth is undefined. (Unless you use setTimeout but that is not a solution)
//Create axios instance
const api = $axios.create({
headers: {
common: {
Accept: 'application/json', //accept json
},
},
})
// Here is the magic, onRequest is an interceptor, so every request made will go trough this, and then we try to access app.$auth inside it, it is defined
api.onRequest((config) => {
// Here we check if user is logged in
if (app.$auth.loggedIn) {
// If the user is logged in we can now get the token, we get something like `Bearer yourTokenJ9F0JFODJ` but we only need the string without the word **Bearer**, So we split the string using the space as a separator and we access the second position of the array **[1]**
const token = app.$auth.strategy.token.get().split(' ')[1]
api.setToken(token, 'Bearer') // Here we specify the token and now it works!!
}
})
// Set baseURL to something different
api.setBaseURL('http://localhost:4100/')
// Inject to context as $api
inject('api', api)
}
Also Nuxt Auth itself has provided a solution for this issue:
https://auth.nuxtjs.org/recipes/extend/

Axios network error even though the post request returns 200

After enabling CORS and everything on my server, the error persists.
In other forms inside my app, uploading pictures works... but in this exact form, on iPhone it works absolutely fine, but on android after submitting, all I get is a "network error" although the post returns 200. I think this is an axios problem. Only on android I get this issue.
my code is the following:
const data = new FormData()
data.append('subject_id', this.props.navigation.getParam('id'))
data.append('name', this.state.title)
data.append('progress', this.state.progress * 100)
data.append('description', this.state.description)
data.append('date', this.state.date)
data.append('image', {
uri: this.state.image,
type: 'image/jpeg',
name: 'image'
});
axios.post('https://example.com/api/auth/createTask', data, {
headers: {
'Authorization': access,
"Content-Type": "multipart/form-data"
},
}).then(res => {
this.props.navigation.navigate('ViewHW', { id: res.data.id })
}).catch(res => {
console.log(res)
})
I would really appreciate the help on this one.
I doubt that it's an axios issue.
If you're using an image picker or camera make sure you check the documentation as the path to the file selected differs between android and iOS.
Make sure you change the path of the item based on platform.OS === 'android'.
It should be clearly described in the docs of whatever you're using.
This ended up being a problem with react-native. The bug is now patched (the new version 0.63.3)

How to minimize data traffic in vuejs

At work, we think about using Vuejs with Vuex for our frontend. I have already used it for private projects.
One of our big questions is the traffic. Our platform needs a lot of data, sometimes in large packages. Some of them are really big and it would be more expensive to load them more than once.
I've seen many examples of vue with vuex, but for me it looked like all the samples would request the same (already loaded) data every time they paged.
My real question is: Is there a way in vuejs or general to avoid or solve this problem? The only helpful thing I have found so far was this.
As far as I know, you can use this library https://github.com/kuitos/axios-extensions
An example here
import Axios from 'Axios';
import { throttleAdapterEnhancer } from 'axios-extensions';
const http = axios.create({
baseURL: '/',
headers: { 'Cache-Control': 'no-cache' },
adapter: throttleAdapterEnhancer(axios.defaults.adapter, { threshold: 2 * 1000 })
});
http.get('/users'); // make real http request
http.get('/users'); // responsed from the cache
http.get('/users'); // responsed from the cache
setTimeout(() => {
http.get('/users'); // after 2s, the real request makes again
}, 2 * 1000)
As you can see, you can create an adaptor and custom what you want. For example here, you keep the cache for only 2 seconds. So the first request to /users is a real one. The second and thirst request are cache, and the last one is after the two seconds, so it's a real one.
Can you be more specific about the context of how you will keep the cache. When do you need to reload the cache, after how many times, after which event, ...?
The strategy I use is to store the value on the Vuex state.
I write all my request in Vuex actions. In every action, I check if the data already exists on the Vuex state. If it does, I simply bypass the request and return the data from the state (saving requests from being called multiple times). If it doesn't exist, I'll make the request, then store the result on the Vuex state, and return the value.
Vuex Action:
getLists({ state, commit }) {
return new Promise((resolve, reject) => {
if (state.isSetLists === false) {
getListsFromServer((error, data) => {
if (error) {
reject(error);
} else {
console.log('call to getLists successful:', data);
commit('setLists', data.lists);
resolve(data.lists);
}
});
} else {
resolve(state.lists);
}
});
},
Then, the setLists mutation handles it like so:
setLists(state, lists) {
state.isSetLists = true;
state.lists = lists;
},
This way, the user can page around all they want, and only ever call each request once.