how to get response from axios with multiable objects? - laravel

I am getting response payload from server like this:
{"0":
[
{"id":1,
"profile_id":"1",
"schoolName":"xx",
"courseName":"xx",
"courseDescription":null,
"created_at":"2020-06-25T09:11:21.000000Z",
"updated_at":"2020-06-25T09:11:21.000000Z"},
{"id":2,
"profile_id":"1",
"schoolName":"yy",
"courseName":"zz",
"courseDescription":"xx",
"created_at":null,
"updated_at":null}
],
"status":"Read Education info successfully!"}
Axios .then response is like this:
.then((response)=>{
vm.setState (
{ educations: Object.values(response.data) },
() => console.log(this.state.datas)
);
})
data- object has educations: []- array inside multiable
education: -objects
Q) how to pass axios response data payload to education object?,
export default {
data() {
return {
educations: [
education: {}],
--- Edit ---
Tried to get response like this:
.then((response)=>{
this.education = response.data.map(value => {
return {
schoolName: value.schoolName,
courseName: value.courseName
}
console.log('Receiving data ....')
})
Vue does not give any error, but I cannot see any data to pass data-object.
In Vuestools:
education : object
courseName: "" is empty.

Related

Split data JSON after data in VueJS

How to split data in JSON if have array after array? This is my JSON format
{
"status": "true",
"error": "",
"data": [
{
"id": 1,
"sections": [
{
"section_id": 1,
"position": []
}
]
}
]
}
So, I'm using AXIOS . This code AXIOS
const url = '/api/v1/form/'
axios
.get(url)
.then(response => {
this.listing = response.data.data;
})
How to call section using this response.data.data.sections ? I'm try but error undefined. Please help me thanks
response.data.data[0].sections
data is an array according to your json so you cannot directly call sections you will have to iterate or select an instance within the array.
the following code should print all section ids //untested code
const url = '/api/v1/form/'
axios
.get(url)
.then(response => {
response.data.data.foreach((listing)=>{
console.log(listing.sections.section_id)
})
})
If you always will have only one entry under data or you want to access only the 1st entry of data you can use response.data.data[0].sections this is a bad way to access it though because if data is empty it will throw you an error . If the case is that you only have one entry under data you should just change your json to be
{
"status": "true",
"error": "",
"data":
{
"id": 1,
"sections": [
{
"section_id": 1,
"position": []
}
]
}
}
and you can then access it directly response.data.data.sections but as long as its an array you will have to treat it as such.
Iterate through sections and positions [as per comments]:
const url = '/api/v1/form/'
axios
.get(url)
.then(response => {
response.data.data.foreach((listing)=>{ //#this will get you each listing(parent object that contains sections array)
listing.sections.foreach((section)=>{//# this will get you each section(parent object that contains position array)
section.position.foreach((el)=>{//# this will get you each elment in the position array as `el`
console.log(el)
})
})
})
})
Try this:
const url = '/api/v1/form/'
axios
.get(url)
.then(response => {
this.listing = response.data;
console.log(this.listing.data) // <-------
})

Writing Structural Expectations with Jest

I am looking to write what I am calling structural expectations with Jest and I am not sure how this could be accomplished.
To start I have a graphql server and a database with a number of todo items. I currently have the following test that just returns true if the content within the database is the same as the response that I have written. I want to check instead that the response looks like an object with data that could be anything.
Here is the code that I have:
describe('To Do:', () => {
it('add todo items', async () => {
const response = await axios.post('http://localhost:5000/graphql', {
query: `
query {
getTodoItems {
message
id
dateCreated
dateDue
}
}
`
});
const { data } = response;
expect(data).toMatchObject({
data: {
getTodoItems: [
{
message: "message",
id: "5bd9aec8406e0a2170e04494",
dateCreated: "1540992712052",
dateDue: "1111111111"
},
{
message: "message",
id: "5bd9aeec60a9b2579882a308",
dateCreated: "1540992748028",
dateDue: "1111111111"
},
{
message: "new message",
id: "5bd9af15922b27236c91837c",
dateCreated: "1540992789836",
dateDue: "1111111111"
}
]
}
})
});
});
Now I want to write something like this, where there can be any number of returned items and they follow similar structuring:
describe('To Do:', () => {
it('add todo items', async () => {
const response = await axios.post('http://localhost:5000/graphql', {
query: `
query {
getTodoItems {
message
id
dateCreated
dateDue
}
}
`
});
const { data } = response;
expect(data).toMatchObject({
data: {
getTodoItems: [
{
message: expect.any(String),
id: expect.any(String),
dateCreated: expect.any(String),
dateDue: expect.any(String)
} // There needs to be unlimited additional items here
]
}
})
});
});
I have been looking throught the docs and I even tried nesting the expectations but I can't seem to get the desired response. Let me know what yo think or if I can clarify in any way.
I figured out the best way for me to do it. I would love to hear better answers. I wrote a function within the scope of the test as a jest.fn and then I called it. In that function, I made custom checks to parse the data that was received in the response. From there I added an expect function with the 'toHaveReturnedWith' method to see what the response of my custom function was and finishing out the test.
const addTodoResponse = jest.fn(() => {
// Custom parsing and check here
// Returns true or false
});
addTodoResponse();
expect(addTodoResponse).toHaveReturnedWith(true);
Are there better ways to do this out there?

promisse value undefined axios

I'm trying to get values using axios and on my browser returns [[PromisseValue]] undefined. Follow my code. Please, help-me... thanks
This is my data to get
<script>
export default {
props: ['endpoint'],
data () {
return {
response: {
table: '',
displayable: [],
records: []
}
}
},
methods: {
getRecords () {
return axios.get(`${this.endpoint}`).then((response) => {
console.log(response.data.data.table)
})
}
},
mounted () {
this.getRecords()
}
}
It will return promise because AXIOS is a promise function that you are trying to return.
axios.get(`${this.endpoint}`).then((response) => {
this.response.table = response.data.data.table
})
after axios call you need save it into your state or data the response then use it wherever you want.

Parse Cloud - Sendgrid with Template

Has anyone been able to use SendGrid templates with Parse Cloud Code?
This works, but only sends text, any ideas on how to use a template_id?
I tried with the filter but was not successful.
Parse.Cloud.define("sendEmail", function(request, response) {
// Import SendGrid module and call with your SendGrid API Key
var sg = require('sendgrid')('your SendGrid API key here');
// Create the SendGrid Request
var reqSG = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: {
personalizations: [
{
to: [
{
// This field is the "to" in the email
email: request.params.toEmail,
},
],
// This field is the "subject" in the email
subject: request.params.subject,
},
],
// This field contains the "from" information
from: {
email: 'info#youremail.com',
name: 'Your Name',
},
// This contains info about the "reply-to"
// Note that the "reply-to" may be different than the "from"
reply_to: {
email: 'info#youremail.com',
name: 'Your Name',
},
content: [
{
type: 'text/plain',
value: request.params.body,
},
],
},
});
sg.API(reqSG, function(SGerror, SGresponse) {
// Testing if some error occurred
if (SGerror) {
// Ops, something went wrong
console.error('Error response received');
console.error('StatusCode=' + SGresponse.statusCode);
console.error(JSON.stringify(SGresponse.body));
response.error('Error = ' + JSON.stringify(SGresponse.body));
}
else {
// Everything went fine
console.log('Email sent!');
response.success('Email sent!');
}
});
});
This is from the documentation on Back4App https://docs.back4app.com/docs/integrations/using-sendgrid-to-send-email/
If anyone is looking for the answer it turned out to be simple,
add the template_id as a personalization and change the message type the text/html,
template_id:"your template_id",
content: [
{
type: 'text/html',
// This field is the body of the email
value: "",
},
],

Axios + Vue + Vuex manipulating a basic GET with deeply nested data

I am trying to make a basic GET call to an API using JSON API specifications with deeply nested relationship data. I'm experiencing an issue with axios or vue manipulating my data...
Paying attention to pickup and delivery relationships, the raw data looks like the following:
{
"data": {
"type": "parent",
"id": "34",
"attributes": {
// ...
},
"relationships": {
"r1": {
"data": [
{
"type": "nextparent",
"id": "62",
"attributes": {
// ..
},
"relationships": {
"pickup": {
"data": [
{
"type": "package",
"id": 521,
"attributes": {
// ...
}
},
// ...
]
},
"delivery": {
"data": []
}
}
},
// ...
]
}
}
}
}
... where pickup has an array of objects and delivery has an empty array. However, when I try to retrieve the response in the callback, delivery is an exact copy of pickup.
var promise = window.axios({
url: window.baseApi + '/my-object/34',
method: 'get'
})
promise.then(function (response) {
console.log(response)
})
Whenever you run console.log(response) in the callback, Vue's observers are applied to the response object, which makes me wonder if this is a Vue issue considering that only the relationships of the first r1 object experience this.
Screenshot of log from callback (incorrect):
Additionally, I checked the response from the axios transformResponse function and the raw json was correct (without observers). This is only happening in the callback.
Screenshot of log from transformResponse (correct):
Will update with fiddle, as soon as I can.
EDIT:
The axios function is being called in a vuex action. Here is the code:
fetchData ({commit, dispatch}) {
var promise = window.axios({
url: window.baseApi + '/my-object/34',
method: 'get'
})
promise
.then(function (response) {
console.log(response)
commit('toggleProgress', {key: 'fetchingData'})
commit('setActive', response.data.data)
dispatch('otherModule/setActiveShipments', response.data.data, {root: true})
dispatch('history/clear')
})
.catch(function () {
//
})
return promise
},

Resources