TypeError: response.data is undefined - vue.js

I'm having problems with promise response for a vForm PUT to UPDATE a model (backend in laravel).
The response code is 200 (OK, updated) and the model is updated, but I don't know why I'm having error with "response.data" in catch. There is no error and code in ".then()" is running correctly.
EDIT
Service Update funciton (vue) using vForm.
updateService(){
this.$Progress.start();
this.service.put('api/service/' + this.service.id)
.then( function (response) {
Toast.fire({
type: 'success',
title: response.data['Response']
});
this.$Progress.finish();
})
.catch( function (response) {
console.log(response);
Swal.fire("Error!", response.data['Response'], "warning");
this.$Progress.fail();
});
this.$events.$emit('ServiceInform');
},
Function in backend (laravel).
public function update(Request $request, Service $service)
{
$this->validate($request, [
'id_customers' => 'required|int',
'date' => 'required|date',
'id_technicians' => 'required|int',
'location' => 'required|string',
'details' => 'required|string'
]);
if ($request['id_technicians'] !== $service['id_technicians']) {
$assignated_by = Auth::user()->id;
$assigned_date = date('Y-m-d H:i:s');
} else {
$assignated_by = $service['assignated_by'];
$assigned_date = $service['assigned_date'];
}
if ($request['id_technicians'] == 0) {
$state = 'P';
} else {
$state = 'I';
}
$service->date = $request['date'];
$service->id_technicians = $request['id_technicians'];
$service->location = $request['location'];
$service->details = $request['details'];
$service->assigned_date = $assigned_date;
$service->assigned_by = $assignated_by;
$service->state = $state;
try {
$service->save();
return Response::json([
'Response' => 'Servicio actualizado.'
], 201);
} catch (Exception $e) {
return Response::json([
'Response' => 'No se actualizó el servicio.'
], 422);
}
}

This line looks problematic to me:
this.$Progress.finish();
It's trying to access this within the function passed to then. It seems unlikely that this will be referencing what you're expecting. You should be able to confirm with suitable console logging. My suspicion is that attempting to call this.$Progress.finish() will throw an error, triggering the catch.
Try using arrow functions for your then and catch callbacks instead.

Related

How can I refresh datatable in Wire using refreshApex

#wire(_getContacts,{recordId:'$recordId'}) wiredContacts({error,data}){
this.dataToRefresh = data;
if (data) {
this.contacts = this.dataToRefresh.recordList;
this.ContactsRecords = this.dataToRefresh.cList;
this.contactsSize = " Case Contacts (" + this.contacts.length + ")";
}else{
//
}
};
relateContacts() {
this.showSpinner = true;
this.showtable=false;
relateContacts({contacts: this.selected, recordId: this.recordId})
.then(data => {
this.showSpinner=false;
this.showtable=true;
this.showSuccessMessage();
refreshApex(this.dataToRefresh);
//location.reload();
this.isShowModal = false;
})
.catch(error => {
console.log(error);
this.showSpinner=false;
const evt = new ShowToastEvent({
title: 'Application Error',
message: error.body.message,
variant: 'error',
mode: 'sticky'
});
this.dispatchEvent(evt);
this.showSpinner = false;
});
}
For this code, I tried refreshApex with all possible ways. but I'm not sure the miss here. I've Checked all the blogs but everywhere, the solution is mentioned.
Tried refreshApex like below :
#wire(_getContacts,{recordId:'$recordId'}) wiredContacts({data}){
this.dataToRefresh = data;
But this also does not work
Ah that is a fun one ! Your issue is using destructuring in wiredContacts as the parameter.
(The {data} or {data,error} normally works as a parameter to the function being called back, except if you have to do refresh) Try this instead.
#wire(_getContacts,{recordId:'$recordId'}) wiredContacts(value){
this.dataToRefresh = value;
const {data, error} = value;
//Rest of you code now with data and error
}
Then in your other method you can do:
method(){
refreshApex(this.dataToRefresh);
}
Salesforce does show doing this in their example code, but it’s easy to miss and experience the fun you have been having with this.
https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_result_caching
See the last example on their page.

Store Auth::user()-id in DB using SQL query in laravel

I want to store Auth::user()->id on the default column user_id in the SQL query shown below.
I tried to set put like this but does not send any data to the database.
public function saveLoadingsData() {
//Validate for a valid Post Request
if (isset($_POST['orderNumber']) && isset($_POST['Truck']) && isset($_POST['receiptNumber']) && isset($_POST['items'])) {
// {"orderNumber":"CRS1104200001","agentId":"3","items":[{"itemId":"4","itemName":"Embe","quantity":"13"}]}
$orderNumber = $_POST['orderNumber'];
$items = $_POST['items'];
$receiptNumber = $_POST['receiptNumber'];
$Truck = $_POST['Truck'];
$driverName = $_POST['driverName'];
foreach ($items as $singleItem) {
$data = array('order_no' => $orderNumber,'user_id'=>Auth::user()->id,"receiptNumber" => $receiptNumber, "Truck" => $Truck, "driverName" => $driverName, "pid" => $singleItem['itemId'], "qty" => $singleItem['quantity']);
// print_r($data);
DB::table('loadings')->insert($data);
// return redirect()->back();
}
// return redirect()->back();
echo "Success";
}
My ajax function
$("#btnSaveOrder").on('click', function(e){
var orderNumber=$("#order_no").val();
var receiptNumber=$("#receiptNumber").val();
var Truck=$("#Truck").val();
var driverName=$("#driverName").val();
var jsonData=convertTableToJson();
$.ajax('/api/loading/saveLoadingsData', {
type: 'POST',
data: {
orderNumber:orderNumber,
receiptNumber:receiptNumber,
Truck:Truck,
driverName:driverName,
items:jsonData
},
success: function (data, status, xhr) {
alert("Data Saved");
document.location.reload(true);
},
error: function (jqXhr, textStatus, errorMessage) {
console.log(errorMessage);
}
});
});
var convertTableToJson = function(){
var rows = [];
$('table#tableSelectedItems tr').each(function(i, n){
if (i!=0) {
var $row = $(n);
rows.push({
itemId: $row.find('td:eq(0)').text(),
itemName: $row.find('td:eq(1)').text(),
quantity: $row.find('td:eq(2)').text(),
});
}
});
return rows;
};
My api route
Route::post('loading/saveLoadingsData', 'LoadingController#saveLoadingsData');
Can someone help me?
I recommend you the following
Pass the $request object in your method and log all object, maybe are missing data and for that reason it does not meet the condition:
saveLoadingsData(Request $request){
Log::info(json_encode($request->all()));`
}
Then check your logs files to see the result in /storage/logs/laravel.log

I am getting this error ,"value for message cannot be cast from double to string"

I am getting this error when I am trying pass object to axios method "value for message cannot be cast from double to string". Does any one have Idea about this.
I have added my two functions.
addNotes = (formData) => {
let noteText = ''
Object.keys(formData).map((item) => {
noteText += formData[item] !== undefined ? `${formData[item]} \n` : ``
})
let localLocation = `${this.state.localAddress.locality}, ${this.state.localAddress.subLocality}`
let { userMetaData, graphListlimit, graphListoffset, imdCode } = this.state
let obj = {
'edEmployeeCode': userMetaData.ed_employee_code,
'edName': userMetaData.ed_name,
'edRoleCode': userMetaData.ed_role_code,
'imdCode': imdCode,
'imdSegment': null,
'bnNoteText': noteText,
'location': localLocation,
'meetingType': this.state.meetingType
}
this.props.onAddNotesAction(obj)
}
export const addNotesAction = (obj) => {
let params = {
ed_employee_code: obj.empCode,
ed_role_code: obj.empRoleCode,
ed_channel: obj.empChannel,
ed_name: obj.edName,
imd_code: obj.imdCode,
imd_segment: null,
bn_note_text: obj.bnNoteText,
location: obj.location,
meeting_type: obj.meetingType
}
return dispatch => {
axios.defaults.headers.common['Authorization'] = obj.token;
axios.post(`${Config.apiRootPath}/meetings/addbranchnote`,
params,
).then(response => {
dispatch(addNotesSuccess(response));
}).catch(err => {
dispatch(addNotesFailure(err.response));
});
};
};

React Native setItem in storage

I have an forEach loop as follows:
let result_test = [];
forEach(result_to_upload, value => {
if (value.picturepath) {
let body = new FormData();
const photo = {
uri: value.picturepath,
type: 'image/jpeg',
name: value.pictureguid + '.jpg',
};
body.append('image', photo);
let xhr = new XMLHttpRequest();
xhr.open('POST', data_url + "/manager/transport/sync/picture/?pictureguid=" + value.pictureguid);
xhr.onload = (e) => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
result_test.push(
{
"vehicle_id": value.vehicle_id,
"slot_id": value.slot_id,
"area": value.area,
"zone": value.zone,
"aisle": value.aisle,
"side": value.side,
"col": value.col,
"level": value.level,
"position": value.position,
"timestamp": value.timestamp,
"picturepath": value.picturepath,
"pictureguid": value.pictureguid,
"reason": value.reason,
"handled": value.handled,
"uploaded": 1
}
);
}
}
};
xhr.onerror = (e) => console.log('Error');
xhr.send(body);
} else {
result_test.push(
{
"vehicle_id": value.vehicle_id,
"slot_id": value.slot_id,
"area": value.area,
"zone": value.zone,
"aisle": value.aisle,
"side": value.side,
"col": value.col,
"level": value.level,
"position": value.position,
"timestamp": value.timestamp,
"picturepath": value.picturepath,
"pictureguid": value.pictureguid,
"reason": value.reason,
"handled": value.handled,
"uploaded": 1
}
)
}
});
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result_test), () => s_cb())
And result to upload is as follows:
[
{
aisle:""
area:""
category_text: "CT"
col:2
color_text:"Argent"
comment:""
handled:0
level:0
make_text:"Peugeot"
model_text:"208"
pictureguid:"88e6a87b-b48b-4bfd-b42d-92964a34bef6"
picturepath:
"/Users/boris/Library/Developer/CoreSimulator/Devices/E5DB7769-6D3B-4B02-AA8F-CAF1B03AFCB7/data/Containers/Data/Application/DBCFB503-F8E1-42FF-8C2B-260A713AF7BC/Documents/2D840EFA-014C-48C0-8122-53D9A0F4A88E.jpg"
position:0
reason:"ENTER"
reference:""
registration:""
side:"E"
slot_id:2358
tag_text:""
timestamp:"201705021714"
uploaded:0
vehicle_id:1
vin:"123456"
zone:"A"
},
{
aisle:""
area:""
category_text: "CT"
col:2
color_text:"Argent"
comment:""
handled:0
level:0
make_text:"Golf"
model_text:"208"
pictureguid:"88e6a87b-b48b-4bfd-b42d-92964a34bef6"
picturepath:""
position:0
reason:"ENTER"
reference:""
registration:""
side:"B"
slot_id:2358
tag_text:""
timestamp:"201705021714"
uploaded:0
vehicle_id:1
vin:"123456"
zone:"A"
}
]
But for some reason is AsyncStorage.getItem("vehicle_slot").then(json => console.log(JSON.parse(json)) only the second object, the first one is not added to storage.
Any advice?
your XMLHttpRequest is going to run asynchronously. It's perfectly possible that your code might get to the
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result_test), () => s_cb())
before the onload event has occurred, since that only happens when the request is done. You should add the setItem as a callback.
resultToUpload.forEach(result => {
if (result.picturepath) {
// handle stuff here
let xhr = new XMLHttpRequest();
xhr.onload = (e) => {
// handle other stuff
result_test.push(/* data */);
await storeInAsyncStorage(result_test, () => s_cb());
};
} else {
// handle even more stuff
result_test.push(/* different data */);
await storeInAsyncStorage(result_test, () => s_cb());
}
});
function storeInAsyncStorage(data, callback) {
if(callback) {
return AsyncStorage.setItem(JSON.stringify(data), callback);
} else {
return AsyncStorage.setItem(JSON.stringify(data));
}
}
You should also be aware that AsyncStorage.setItem is asynchronous. The item does not get set immediately, and the setItem method returns a promise that resolves when the item is set. Try using await AsyncStorage.setItem if you're not passing it into some other function.

sinon stub is not working

I'm quiet new into testing and I don't seem to succeed to succesfully stub a function. I'm trying to stub the connection to the database, but it keep's contacting it, instead of using the result from the stub:
Here's the function:
var self = module.exports = {
VerifyAuthentication: function (data){
var deferred = q.defer()
if(typeof(data.email)=='undefined'){
deferred.reject({data:{},errorcode:"",errormessage:"param 'email' is mandatory in input object"})
}else{
if(typeof(data.password)=='undefined'){
deferred.reject({data:{},errorcode:"",errormessage:"param 'password' is mandatory in input object"})
}else{
var SqlString = "select id, mail, password, origin from tbl_user where mail = ?"
var param = [data.email]
self.ExecuteSingleQuery(SqlString, param).then(function(results){
if(results.length > 0)
{
if (results[0].password == data.password)
{
deferred.resolve({data:{"sessionId":results[0].id},errorcode:"",errormessage:""})
}else{
deferred.reject({data:{},errorcode:"",errormessage:"bad password"})
}
}else{
deferred.reject({data:{},errorcode:"",errormessage:"unknown user"})
}
})
}
}
return deferred.promise
},
ExecuteSingleQuery: function (queryString, parameters){
var deferred = q.defer()
var connection = connect()
connection.query(queryString, parameters, function (error, results, fields){
if(error){ deferred.reject(error)};
deferred.resolve(results)
});
return deferred.promise
},
And here's the test:
var dbconnection = require('../lib/dbConnection.js')
describe("VerifyAuthentication", function(){
it("_Returns DbResult object when user name and password match", function(){
var expectedResult = {data:{"sessionKey":"b12ac0a5-967e-40f3-8c4d-aac0f98328b2"},errorcode:"",errormessage:""}
stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').returns(Promise.resolve(expectedResult))
return dbconnection.VerifyAuthentication({email:"correct#adres.com",password:"gtffr"}).then((result)=>{
expect(result.data.sessionId).to.not.be.undefined
expect(result.errorcode).to.not.be.undefined
expect(result.errormessage).to.not.be.undefined
stub.restore()
})
})
})
I always got an error 'unknown user', which is normal, because the user is indeed not in the database. However, I want to stub the 'ExecuteSingleQuery' function, avoiding it to connect to DB.
I have fixed a couple of issues in your code and posting the corrected files below.
dbConnection.js
var self = module.exports = {
VerifyAuthentication: function (data) {
var deferred = q.defer();
if (typeof (data.email) == 'undefined') {
deferred.reject({
data: {},
errorcode: '',
errormessage: "param 'email' is mandatory in input object"
});
} else {
if (typeof (data.password) == 'undefined') {
deferred.reject({
data: {},
errorcode: '',
errormessage: "param 'password' is mandatory in input object"
});
} else {
var SqlString = 'select id, mail, password, origin from tbl_user where mail = ?';
var param = [data.email];
self.ExecuteSingleQuery(SqlString, param).then(function (results) {
if (results.length > 0) {
if (results[0].password === data.password) {
deferred.resolve({
data: {
'sessionId': results[0].id
},
errorcode: '',
errormessage: ''
});
} else {
deferred.reject({
data: {},
errorcode: '',
errormessage: 'bad password'
});
}
} else {
deferred.reject({
data: {},
errorcode: '',
errormessage: 'unknown user'
});
}
});
}
}
return deferred.promise;
},
ExecuteSingleQuery: function (queryString, parameters) {
var deferred = q.defer();
var connection = connect();
connection.query(queryString, parameters, function (error, results, fields) {
if (error) {
deferred.reject(error);
}
deferred.resolve(results);
});
return deferred.promise;
}
};
dbConnection.test.js
describe('VerifyAuthentication', function () {
it('Returns DbResult object when user name and password match', function () {
var expectedResult = [{
id: '123',
password: 'gtffr'
}];
const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult);
return dbconnection.VerifyAuthentication({
email: 'correct#adres.com',
password: 'gtffr'
}).then((result) => {
expect(result.data.sessionId).to.not.be.undefined;
expect(result.errorcode).to.not.be.undefined;
expect(result.errormessage).to.not.be.undefined;
stub.restore();
});
});
});
I am outlining the problematic parts below:
The expectedResult variable had a wrong type of value. In the
self.ExecuteSingleQuery() implementation you check for an array with length > 0. The fixed result returned by the stub, was an object instead of an array and this is why it returned the unknown user exception
The array should contain an object with { id: 'xxx', password: 'gtffr' } attributes. Password is validated against the one used by the dbconnection.VerifyAuthentication({email:"correct#adres.com",password:"gtffr"}) call
Finally, I have changed the stub statement to resolve instead of return as shown here const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult); - this is the preferred method of resolving a promise