Array issue with Vuejs and axios - vue.js

Hi I receive an answer from an axios like this:
axios.post('/api/hr_employee/days/'+ this.period_data.year +'/'+ this.period_data.month +'?page='+this.currentPage+'&api_token='+App.apiToken)
.then(response => {
this.posts = JSON.stringify(response.data.data);
console.log(this.posts.rut);
this.rowsQuantity = JSON.stringify(response.data.data.rut.length);
})
If I check the response it displays:
console.log(JSON.stringify(response.data.data));
{"rut":["06152617-K","06628494-8","06802969-4","06974036-7","07066149-7","07174172-9","07274753-4","07835227-2","08068401-0","08142157-9","08602937-5","08820315-1","08883533-6","09134412-2","09360615-9","09426000-0","09482390-0","09535406-8","09874855-5","10033721-5","10033741-K","10137545-5","10313233-9","10431151-2","10626085-0","10628514-4","10642899-9","10725575-3","10750262-9","10790603-7","10923452-4","10963260-0","11099111-8","11155155-3","11166398-K","11243121-7","11656483-1","11670463-3","11694645-9","11756501-7","11813180-0","11831400-K","11849551-9","11938713-2","12025353-0","12069398-0","12233298-5","12252924-K","12297111-2","12501219-1","12642557-0","12791259-9","12793546-7","12885196-8","12921934-3","12996111-2","13042688-3","13175573-2","13252171-9","13405296-1","13492547-7","13708510-0","13764500-9","13917718-5","14003387-1","14008227-9","14313469-5","14352987-8","14481738-9","14594420-1","15050542-9","15081798-6","15538007-1","15583027-1","15757306-3","15808735-9","15910256-4","15918421-8","15947022-9","16281232-7","16404869-1","16411890-8","16543379-3","16698947-7","16727358-0","16787383-9","16788913-1","16849126-3","17113779-9","17125113-3","17128461-9","17200607-8","17258553-1","17292825-0","17390237-9","17707004-1","17927553-8","17995199-1","18202568-2","18239456-4","18255994-6","18267465-6","18273096-3","18291733-8","18566961-0","18579236-6","18657051-0","18805028-k","18842465-1","18987839-7","19068615-9","19181860-1","19208732-5","19229525-4","19355444-K","19390553-6","19640455-4","19677914-0","19691447-1","19844084-1","19903195-3","19966543-K","20057484-2","20060059-2","20226059-4","20227575-3","20260330-0","20406658-2","20483426-1","20729074-2","20800385-2","20998161-0","21828453-1","21902443-6","22588139-1","22845770-1","23468753-0","23645227-1","23881022-1","24623559-7","24658304-8","24773648-4","24811238-7","24959860-7","25215942-8","25259612-7","25310541-0","25310683-2","25310734-0","25383726-8","25486922-8","25705970-7","25939855-K","26057740-9","26072855-5","26173938-0","26299443-0","26303301-9","26380591-7","26488988-k","26567665-0","26597593-3","26598819-9","26803446-3","26868737-8","26913967-6","26980959-0","27008182-7","27008183-5","27029453-7","27141399-8","27231254-0","27474935-0"],"full_name":["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"total_days":[30,30,30,21,30,30,30,30,30,30,30,30,30,30,27,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,1,30,30,30,26,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,17,30,30,30,30,30,30,30,30,30,30,29,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,26,30,30,30,30,1,30,30,16,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]}
BUT if I do this
this.posts = JSON.stringify(response.data.data);
console.log(this.posts.rut);
undefined
so I wonder why does it display undefined if this.posts has same value? how can I fix it?
Thanks

I think it is because you stringify the response.data.data so this.posts data type become string. The string don't have rut property. That cause undefined when you log it.
I guess you don't need to JSON.stringify the response.data.data
try
this.posts = response.data.data;
this.rowsQuantity = response.data.data.rut.length;

That's because response from Axios is already in JSON format, but you are converting it to a string. To fix this issue, change the following line
From this:
this.posts = JSON.stringify(response.data.data);
To this:
this.posts = response.data.data;
You shall then be able to access the properties within the this.posts object

that's because you're trying to use the property access operator in a String value. You could fix that by calling JSON.parse(response.data.data) but I believe that axios already parses the response for you, so I think you can avoid using JSON.stringify.
JSON.stringify() returns a String value. You're getting undefined and not an error because Javascript does something called Object Wrapping (in this case it does new String(...))

Related

Same situation but different results. I think that Try syntax might be the cause [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 months ago.
I encountered axios error in the process of creating my application.
The below code work fine.
in the first image,console.log output res.data.
let categoryId = ''
axios.get('/api/max')
.then((res) => {
console.log(res.data) // image part
categoryId = res.data.id
})
.catch((err) => {
console.log('ssssssuuuuu')
})
('api/max') return category with max ID.
The below code don't work well.
console.log(res) output properly, but console.log(res.data) output undefined.
try {
const res = axios.get('/api/max')
console.log(res)
console.log(res.data) // undefined
categoryId = res.data.id
console.log('a')
} catch (err) {
console.log(err.message)
}
what causes undefined?
I googled but, I didn't know the cause.
I'm sorry that my English is not very good.
Thank you for your help.
You should use await axios.get('/api/max') before using console.log since it's an async call. (you can also use .then but it's less friendly)
Of course, don't forget to wrap your function into an async when using await.
Also, keep in mind that quirk when using console.log. Prefer using Vue devtools to inspect the current state you do have on your page.
Overall, I recommend the usage of async/await over .then all the time.
Here is a nice documentation for that one: https://javascript.info/async-await

Understanding then() in Cypress

I am reading through the documentation in Cypress and I think I have an idea as to what then() does. It works like promises, where a promise returns another promise, but with then(), we are returning a new subject.
If we look at the code example below, we are using then() because we are returning a new variable, which in this case is called target.
Am I understanding this correctly? If not, can someone correct me?
it.only('Marks an incomplete item complete', () => {
//we'll need a route to stub the api call that updates our item
cy.fixture('todos')
.then(todos => {
//target is a single todo, taken from the head of the array. We can use this to define our route
const target = Cypress._.head(todos)
cy.route(
"PUT",
`api/todos/${target.id}`,
//Here we are mergin original item with an object literal
Cypress._.merge(target, {isComplete: true})
)
})
.then is used to receive the results from cy.fixture('todos'). The variable target is not significant in this code.
In your code sample, the variable that is returned from cy.fixture is named todos - the spacing of the code may be throwing you off here? The .then call is attached to the cy.fixture() call
// These 2 code blocks are the same - just different spacing
cy.fixture('todos')
.then(todos => {});
cy.fixture('todos').then(todos => {});
https://docs.cypress.io/api/commands/fixture.html#Usage
cy.fixture('logo.png').then((logo) => {
// load data from logo.png
})
Using .then() allows you to use the yielded subject in a callback function and should be used when you need to manipulate some values or do some actions.
To put it simply, it is used to play around with the yield of the previous command and work around with it in that case. THEN() command is handy and helpful in debugging the yield of the previous command.
const baseURL = "https://jsonplaceholder.typicode.com";
describe("Get Call-Expect+ normal req", () => {
it("GetPostById-Expect", () => {
cy.request(baseURL + "/posts/1").as("GetPostById");
cy.get("#GetPostById").then((response) => {
//response: status
expect(response.status).to.equal(200);
expect(response.status).to.eq(200);
});
});
Refer: https://docs.cypress.io/api/commands/then#Promises

Can't get the data from Object

I am confused with the data.
AsyncStorage.getItem('deviceuuid', (err, result) => {
console.log('result =>', result);
console.log('result.rawData =>', result.rawData);
})
console.log will show
Why result.rawData is undefined ?
Try JSON.parse(result.rawData)
That's because you are getting an String. AsyncStorage.getItem() returns an String and is likely that that string were a json before.
To resolve this, parse the result to a json.
const resultJSON = JSON.parse(result);
console.log('result.rawData =>', resultJSON.rawData);
The console shows that the data is in JSON format. But you can get the data without Parse.
let rawdata = await AsyncStorage.getItem ( 'deviceuuid');
console.log (rawdata);

Async/await calls with axis and Vue.js - `.then()` callback not updating `this.something`

I'm having a little trouble setting one of my this.values within my Vue application. I believe I'm either not understanding async axios calls correctly, or how async works within axios.
I have the following axios post method within my Vue application:
postRequest: async function(event) {
event.preventDefault();
let config = {
headers: {
"X-CSRFToken": this.csrfToken,
"Content-Type": 'application/x-www-form-urlencoded',
}
}
let formData = new FormData();
formData.append('data', someData);
await axios.post('{{ request_absolute_uri }}', formData, config).then(function(response) {
this.responseMessage = response.data.message;
}).catch(function(error) {
console.log(error);
});
}
console.log(this.responseMessage)
return this.responseMessage;
}
My response.data.message is being passed back from my framework as True/true but it seems I'm not returning anything from the postRequest function? The post definitely hits the server as logging shows everything I want - then returns back message = true in json response context (using console.log(this.responseMessage) directly before returning the same value. However, nothing on the template changes or updates from this....
I'm assuming at this point that I have missed something incredibly simple!
Hmmm. I think I know what is going on here: because you're using a standard function, your this inside the .then() callback is not refering to the instantiated object...instead, this. is the calling the context of that function - with your original code, i.e., the Promise returned by the axios .post method.
Instead, I would advise using an arrow function instead so that the this is inherited from the outer scope, something along these lines:
await axios.post('{{ request_absolute_uri }}', formData, config).then( (response) => {
this.responseMessage = response.data.message;
})
N.B. With arrow functions, the this. is always inherited from the outer scope, rather than depending on the calling context of the arrow function - so you can reference this.message or this.someFunction() with ease.
I believe the "this" is out of scope inside .then statement. If you add the line:
var self = this;
at the top of your postRequest function, and then when assigning the response message use:
self.responseMessage = response.data.message;
I think that should work.

Component method response object data binding

I am starting to lose my mind in debugging an application that I inherited from a fellow developer who is absent.
I have narrowed down the problem to the following place in code (php files are checked, Vue instances are initialised, there are no syntax errors).
This is my the component that gets initialised:
var RadniStol = Vue.component('radnistol', {
template: '#template-RadniStol',
data() {
return {
tableData: [],
requestData: {
sort: "ID",
order: "DESC"
}
}
},
methods: {
reloadTable: function (event) {
data = this.requestData;
this.$http.post('php/get/radni_stol.php', data).then(response => {
console.log(response.data.bodyText);
this.tableData = response.data.records;
});
},
.
.
.
The PHP file that gets called with the POST method is working correctly, querying the database and echoing the response in a JSON format.
The thing that is making me pull out my hair is the following: the console.log(response.data) outputs the following into the console:
{"records":[{"DODAN_NA_RADNI_STOL":"1","..."}]}
It is an JSON object that I expected to have but when trying to assign it to the data of the component with:
this.tableData = response.data;
or any other way… response.data.records returns ‘undefined’ in the console. I have tryed with JSON.parse() but no success.
When logging types to console:
response variable is a response object with a status 200 and body and bodyText containing the data from the database.
response.data is a string type containing the string JSON with the data from the database.
When trying to use JSON.parse(response.data) or JSON.parse() on anything in the callback of the POST method I get the following error in the console:
RadniStol.js?version=0.1.1:17 Uncaught (in promise) SyntaxError: Unexpected token in JSON at position 0
at JSON.parse (<anonymous>)
at VueComponent.$http.post.then.response (RadniStol.js?version=0.1.1:17)
at <anonymous>
I am really starting to lose my mind over this issue, please help!
Thank you
If response.data is string, with JSON inside, then to access the records field, you should decode it like this:
JSON.parse(response.data).records
Not sure this has something to do with PHP or Vue.js, it is just plain javascript issue.
If it not decodes, than problem is definitely in response.data. For example
{"records":[{"DODAN_NA_RADNI_STOL":"1","..."}]}
is not a valid JSON, because key "..." needs to have some value.
But it seems to me that response.data is already parsed.
What I suggest you to do, is to write handler of the response as separate function, make response object that mimics actual response object by hand, and then test it separately from request. So you could show us request object and function that works with it.
I had the same error and fixed it.
Result will be response.body not response.data.
Here is my code:
getS: function(page) {
this.$http.get('vue-manager?page=' + page).then((response) => {
var data = JSON.parse(response.body);
this.student = data.data.data;
this.pagination = data.pagination;
});
},