(VUEJS) Access methods from Axios inside created - vue.js

I have just a simple error which is confusing me almost 3 weeks.
my question is about, I want to return string from methods "idvideo" at the end of my axios API url, but nothing is happen.
as you can see on my code below.
I have been searching for solution and try an error for many times, but still never found any best answer that can help me out.
export default {
data() {
return {
errors: [],
videos: [],
items: []
}
},
methods: {
idvideo: function() {
const data = this.items
const result = data.map((item) => {
return {
fetchId: item.snippet.resourceId.videoId
};
}).sort((a, b) => b.count - a.count);
var i, len, text;
for (i = 0, len = result.length, text = ""; i < len; i++) {
text += result[i].fetchId + ",";
}
var x = text.slice(0, -1);
return(x);
}
// Fetches posts when the component is created.
created() {
// Ini adalah API utk playlist yang dipilih
axios.get("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLjj56jET6ecfmosJyFhZSNRJTSCC90hMp&key={YOUR_API_KEY}")
.then(response => {
// JSON responses are automatically parsed.
this.items = response.data.items
})
.catch(e => {
this.errors.push(e)
}),
// Ini adalah API utk data yang dipilih
axios.get('https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&key={YOUR_API_KEY}&id='+this.idvideo())
.then(response => {
// JSON responses are automatically parsed.
this.videos = response.data.items
})
.catch(e => {
this.errors.push(e)
})
},
}
I really appreciate any kind of solutions that can help me out. If you guys have best way to implement this function, let me know.
Sorry for my bad english and any mistakes. This is my very second time post question in this platform.
Thank you very much sir!

Since, they are asynchronous requests, I have following solution in my mind.
Solution:
Move the next axios call within the first axios call. This is because, only after first call, the 'items' will be retrieved and then it will assigned to this.items So next axios call will have the required data from idvideo() function.
export default {
data() {
return {
errors: [],
videos: [],
items: []
}
},
methods: {
idvideo: function() {
const data = this.items
const result = data.map((item) => {
return {
fetchId: item.snippet.resourceId.videoId
};
}).sort((a, b) => b.count - a.count);
var i, len, text;
for (i = 0, len = result.length, text = ""; i < len; i++) {
text += result[i].fetchId + ",";
}
var x = text.slice(0, -1);
return(x);
}
// Fetches posts when the component is created.
created() {
// Ini adalah API utk playlist yang dipilih
axios.get("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLjj56jET6ecfmosJyFhZSNRJTSCC90hMp&key={YOUR_API_KEY}")
.then(response => {
// JSON responses are automatically parsed.
this.items = response.data.items
// Ini adalah API utk data yang dipilih
axios.get('https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&key={YOUR_API_KEY}&id='+this.idvideo())
.then(response => {
// JSON responses are automatically parsed.
this.videos = response.data.items
})
.catch(e => {
this.errors.push(e)
})
}
})
.catch(e => {
this.errors.push(e)
}),
,
}

Related

Variable in data section can't get API response value (response.data)

I accessed API to upload image and return the image URL with Vue app. I want to set API response value to imgUrl1 in data section. I' sure getting correct response in console but imgUrl1 is still empty. Anybody idea ?? Thank you so much !
Vue
data () {return
{
imgUrl1:'',→empty
}
},
methods: {
uploadFile1: function () {
var img_file1 = this.$refs.img1.files[0]
var params = new FormData()
params.append('image', img_file1)
params.append('client_name', this.tableSelected)
axios.post("http://127.0.0.1:5000/", params
).then(function (response) {
console.log(response.data)→image url exists
this.imgUrl1 = response.data
}).catch(function (error) {
for(let key of Object.keys(error)) {
console.log(key);
console.log(error[key]);
}
});
}
console.log(response.data)
https://storage.googleapis.com/dashboard_chichat/img/クライアント名/xxxxxxxxnQSkX6Wudy.jpg
try using arrow functions in your then callback so the value of this is your Vue component.
methods: {
uploadFile() {
...
axios.post('', params)
.then((response) => {
this.imgUrl1 = response.data
})
}
}
the equivalent of it without arrow functions is:
methods: {
uploadFile() {
...
const _this = this;
axios.post('', params)
.then(function (response) {
_this.imgUrl1 = response.data
})
}
}

How to encode and parse / decode a nested query string Javascript

I'm sending form data from React Hook Form to Netlify via their submission-created function. I don't have any problem with encoding individual form field values, but now I'm trying to encode an array of objects.
Here is an example of my form data:
{
_id: "12345-67890-asdf-qwer",
language: "Spanish",
formId: "add-registration-form",
got-ya: "",
classType: "Private lessons",
size: "1",
days: [
{
day: "Monday",
start: 08:00",
end: "09:30"
},
{
day: "Wednesday",
start: "08:00",
end: "09:30"
}
]
}
The only problem I have is with the "days" array. I've tried various ways to encode this and this is the function I've currently been working with (which isn't ideal):
const encode = (data) => {
return Object.keys(data).map(key => {
let val = data[key]
if (val !== null && typeof val === 'object') val = encode(val)
return `${key}=${encodeURIComponent(`${val}`.replace(/\s/g, '_'))}`
}).join('&')
}
I tried using a library like qs to stringify the data, but I can't figure out how to make that work.
And here is the function posting the data to Netlify:
// Handles the post process to Netlify so I can access their serverless functions
const handlePost = (formData, event) => {
event.preventDefault()
fetch(`/`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({ "form-name": 'add-registration-form', ...formData }),
})
.then((response) => {
if(response.status === 200) {
navigate("../../")
} else {
alert("ERROR!")
}
console.log(response)
})
.catch((error) => {
setFormStatus("error")
console.log(error)
})
}
Finally, here is a sample of my submission-created file to receive and parse the encoded data:
const sanityClient = require("#sanity/client")
const client = sanityClient({
projectId: process.env.GATSBY_SANITY_PROJECT_ID,
dataset: process.env.GATSBY_SANITY_DATASET,
token: process.env.SANITY_FORM_SUBMIT_TOKEN,
useCDN: false,
})
const { nanoid } = require('nanoid');
exports.handler = async function (event, context, callback) {
// Pulling out the payload from the body
const { payload } = JSON.parse(event.body)
// Checking which form has been submitted
const isAddRegistrationForm = payload.data.formId === "add-registration-form"
// Build the document JSON and submit it to SANITY
if (isAddRegistrationForm) {
// How do I decode the "days" data from payload?
let schedule = payload.data.days.map(d => (
{
_key: nanoid(),
_type: "classDayTime",
day: d.day,
time: {
_type: "timeRange",
start: d.start,
end: d.end
}
}
))
const addRegistrationForm = {
_type: "addRegistrationForm",
_studentId: payload.data._id,
classType: payload.data.classType,
schedule: schedule,
language: payload.data.language,
classSize: payload.data.size,
}
const result = await client.create(addRegistrationForm).catch((err) => console.log(err))
}
callback(null, {
statusCode: 200,
})
}
So, how do I properly encode my form data with a nested array of objects before sending it to Netlify? And then in the Netlify function how do I parse / decode that data to be able to submit it to Sanity?
So, the qs library proved to be my savior after all. I just wasn't implementing it correctly before. So, with the same form data structure, just make sure to import qs to your form component file:
import qs from 'qs'
and then make your encode function nice and succinct with:
// Transforms the form data from the React Hook Form output to a format Netlify can read
const encode = (data) => {
return qs.stringify(data)
}
Next, use this encode function in your handle submit function for the form:
// Handles the post process to Netlify so we can access their serverless functions
const handlePost = (formData, event) => {
event.preventDefault()
fetch(`/`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({ "form-name": 'add-registration-form', ...formData }),
})
.then((response) => {
reset()
if(response.status === 200) {
alert("SUCCESS!")
} else {
alert("ERROR!")
}
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
Finally, this is what your Netlify submission-created.js file should look like more or less:
const sanityClient = require("#sanity/client")
const client = sanityClient({
projectId: process.env.GATSBY_SANITY_PROJECT_ID,
dataset: process.env.GATSBY_SANITY_DATASET,
token: process.env.SANITY_FORM_SUBMIT_TOKEN,
useCDN: false,
})
const qs = require('qs')
const { nanoid } = require('nanoid');
exports.handler = async function (event, context, callback) {
// Pulling out the payload from the body
const { payload } = JSON.parse(event.body)
// Checking which form has been submitted
const isAddRegistrationForm = payload.data.formId === "add-registration-form"
// Build the document JSON and submit it to SANITY
if (isAddRegistrationForm) {
const parsedData = qs.parse(payload.data)
let schedule = parsedData.days
.map(d => (
{
_key: nanoid(),
_type: "classDayTime",
day: d.day,
time: {
_type: "timeRange",
start: d.start,
end: d.end
}
}
))
const addRegistrationForm = {
_type: "addRegistrationForm",
submitDate: new Date().toISOString(),
_studentId: parsedData._id,
classType: parsedData.classType,
schedule: schedule,
language: parsedData.language,
classSize: parsedData.size,
}
const result = await client.create(addRegistrationForm).catch((err) => console.log(err))
}
callback(null, {
statusCode: 200,
})
}

Axios store same information inside foreach

I have an array of objects that is needed to be store in DB when clicking on a single button. Therefore I have used foreach loop and inside the loop, I did the AXIOS POST. AXIOS stores the same information/ object. all objects of the array are not saved is there any solution.
let arr = [
{
name:'abc',
co: 1
},
{
name:'def',
co: 2
},
{
name:'ghi',
co: 3
},
];
let fd = new FormData();
arr..forEach((element) => {
fd.append("name", element.name);
fd.append("co", element.co);
this.$http.post("po", fd, { headers: {
"Content-Type": "multipart/form-data",
},
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
});
WHEN MAPPING THE ARRAY as follows. an error occurs cannot read property co of undefined
let element= this.formList.map((obj) => obj);
// appending data
// axios POST
IT ONLY SAVES THE LAST OBJECT. WHAT I WANT IS EACH OBJECT SHOULD BE STORE
the mistake I did was putting the Axios inside the foreach, which overwrites the object each time it loops therefore only the last item gets stored. the working solution is below
save() {
this.StoreMulti(this.arr, 0);
}
StoreMulti(arr, i){
this.$http.post("po", fd, { headers: {
"Content-Type": "multipart/form-data",
},
.then((res) => {
if (i < arr.length - 1) {
this.StoreMulti(arr, ++i);
}
onsole.log(res.data);
})
.catch((err) => {
console.log(err);
});
}
THIS STORE THE ENTIRE ARRAY BY SENDING POST REQUEST ONE BY ONE

How to place a component's logic outside the file .vue itself

I'm building a webapp in Nuxt.js and it's growing quite a bit.
I have a page which does two things: one when i'm creating a task and one when managing that task.
This page has a lot of methods, divided for when i create the task and when i manage the task.
How can i split these modules in two files and then import then only when I need them?
These methods need also to access the component's state and other function Nuxt imports such as axios.
async create() {
if (this.isSondaggioReady()) {
try {
await this.getImagesPath()
const o = { ...this.sondaggio }
delete o.id
o.questions = o.questions.map((question) => {
delete question.garbageCollector
if (question.type !== 'checkbox' && question.type !== 'radio') {
delete question.answers
delete question.hasAltro
} else {
question.answers = question.answers.map((answer) => {
delete answer._id
delete answer.file
delete answer.error
if (answer.type !== 'image') delete answer.caption
return answer
})
}
if (question.hasAltro) {
question.answers.push({
type: 'altro',
value: ''
})
}
return question
})
console.log('TO SEND', JSON.stringify(o, null, 2))
this.$store.commit('temp/showBottomLoader', {
show: true,
message: 'Crezione del sondaggio in corso'
})
const { data } = await this.$axios.post('/sondaggi/admin/create', o)
this.sondaggio.id = data
const s = {
_id: data,
author: this.$auth.user.email.slice(0, -13),
title: this.sondaggio.title
}
this.$store.commit('temp/pushHome', { key: 'sondaggi', attr: 'data', data: [...this.$store.state.temp.home.sondaggi.data, s] })
this.$store.dispatch('temp/showToast', 'Sondaggio creato correttamente')
this.$router.replace('/')
} catch (e) {
console.log(e)
this.$store.dispatch('temp/showToast', this.$getErrorMessage(e))
} finally {
this.$store.commit('temp/showBottomLoader', {
show: false,
message: 'Crezione del sondaggio in corso'
})
}
}
},
Here there's an example of what a method does. It calls an async functions which relies on HTTP axios requests:
async getImagesPath() {
this.sondaggio.questions.forEach((question, i) => {
question.answers.forEach((answer, j) => {
if (answer.file instanceof File || answer.value.includes('data:image')) {
this.uploadingImages.push({
coords: [i, j],
percentage: 0,
file: answer.file || answer.value
})
}
})
})
const requests = []
this.uploadingImages.forEach((img) => {
const temp = new FormData()
temp.append('img', img.file)
const req = this.$axios.post('/sondaggi/admin/images/add/' + this.sondaggio.title.replace(/\s+/g, ''), temp, {
onUploadProgress: function (progressEvent) {
img.percentage = Math.round(((progressEvent.loaded * 100) / progressEvent.total) * 90 / 100)
},
onDownloadProgress: function (progressEvent) {
img.percentage = 90 + Math.round(((progressEvent.loaded * 100) / progressEvent.total) * 10 / 100)
},
headers: { 'Content-Type': 'multipart/form-data' }
})
.catch((err) => {
console.log(err)
img.percentage = 150
})
requests.push(req)
})
try {
const response = await Promise.all(requests)
response.forEach(({ data }, i) => {
this.sondaggio.questions[this.uploadingImages[i].coords[0]].answers[this.uploadingImages[i].coords[1]].value = data[0]
})
this.$set(this.sondaggio, 'hasImages', this.uploadingImages.length > 0)
this.uploadingImages = []
await Promise.resolve()
} catch (e) {
console.log('handling gloval err', e)
await Promise.reject(e)
}
},
As you can see axios requests modify the component's state

Cannot read property of "then" of undefined APOLLO GRAPHQL

I'm having a trouble and i'm stuck. I used to replicate this on my other codes but this method doesn't work on apollo. Here is my method using the apollo on my vue.js.
handleLikePost() {
const variables = {
postId: this.postId,
username: this.user.username
};
this.$apollo.mutate({
mutation: LIKE_POST,
variables,
update: (cache, { data: { likePost } }) => {
const data = cache.readQuery({
query: GET_POST,
variables: { postId: this.postId }
});
data.getPost.likes += 1;
cache
.writeQuery({
query: GET_POST,
variables: { postId: this.postId },
data
})
.then(({ data }) => {
// const updatedUser = {
// ...this.user,
// favorites: data.likePost.favorites
// };
//this.$store.commit("setUser", updatedUser);
console.log(this.user);
console.log(data.likePost);
})
.catch(err => console.error(err));
}
});
}
I think the problem is you are not returning something from;
cache.writeQuery()
That's why .then({data}) is not getting something from writeQuery()