React-native typescript error: Type 'Generator<any, any, unknown>' is missing the following properties from type - react-native

I have a function to return an object named UploadToGetId that I defined myself and it worked in runtime, but I got an error in compile time
Type 'Generator<any, any, unknown>' is missing the following properties from type 'UploadToGetID': imageId, imageThumbId
This is my code:
type UploadToGetID = {
imageId: string | undefined;
imageThumbId: string | undefined;
};
function* uploadImageOrVideoToGetId(
image: Image | undefined,
imageThumb: ImageThumb | undefined,
): UploadToGetID {
const uploadId: UploadToGetID = {
imageId: undefined,
imageThumbId: undefined,
};
try {
if (image) {
const token = yield Helper.getDataStored(JWT_KEY);
let newImage: ImageResizerResponse = yield call(
ImageResizer.createResizedImage,
imageThumb!.url!,
5000,
5000,
'JPEG',
100,
);
let file = newImage.uri;
if (Platform.OS === 'android') {
file = newImage.uri.replace('file://', '');
}
...
} catch (error) {
Alert.alert('Upload image fail! ' + error);
return uploadId;
}
}
Help me if you know how to fix it

Related

Vue js MQTT connection problems

I want to put 'mqtt' value in span. But it doesn't work.
I think the loading method is wrong, but I don't know how to do it.
I don't know if the code below will suffice. Any help would be greatly appreciated.
Someone else coded similar to one page. Someone else's code has a value in 'detail', but my code doesn't. Why?
HTML
span{{ detail }}span //empty with nothing
Front script1
export default {
props: {
detail: {
type: Object
},
isAdd: {
type: Boolean,
default: false
},
},
data() {
return {};
},
mounted() {
this.$mqtt.subscribe('#');
},
methods: {
SendData() {
var temp = [];
var name = Number(document.getElementsByClassName('name').innerHTML);
temp.push(name);
var temp_current = data.payload.Temp_Current;
var error = data.payload.Error;
var data = {
//workcd: this.detail.namemodel,
Temp_Current: temp_current,
Error: error,
};
data = JSON.stringify(data);
var pub_name_arr = this.detail.name.split(' ');
var pub_name = 'CCComandTopic';
this.$mqtt.publish(
pub_name + '/' + pub_name_arr[1] + '/' + pub_name_arr[2],
data,
);
},
}
}
Front script 2
showHotrunner(namemodel, name, data) {
this.$modal.show(
Hotrunner,
{detail: {namemodel, name, data}, isAdd: true},
{width: '1040', height: '700', draggable: true},
);
const canvas = document.getElementById('three-canvas');
canvas.classList.add('noclick');
}
Back
var device = msg.topic.split("/")[2]
if(device == "hopper")
{
var temp_current = msg.payload.Temp_Current
var error = msg.payload.error
msg = {
topic : "CCComandTopic/hopper/1",
payload : {
ID: id,
"Error": error,
Temp_Current: temp_current,
}
}.
node.send(msg)
}

How can I send image in react-native-gifted-chat?

I want to send image in react-Native-Gifted-chat like sending text. I am novice in react-native.
I have already used react-native-image-picker for pick a image from physical device, now I am unable to render image in message[].
You can call the onSend method of GiftedChat with an object as a parameter. Just pass an object with image as key. For example
onSend({ image: "https://picsum.photos/id/237/200/300" });
you can use this
import DocumentPicker from 'react-native-document-picker';
install this library first
then simply choose the file from the document picker
use this function
onAttatchFile = async () => {
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.allFiles],
});
// console.log(res);
let type = res.name.slice(res.name.lastIndexOf('.') + 1);
if (
res.type == 'doc' ||
res.type == 'application/pdf' ||
res.type == 'image/jpeg' ||
res.type == 'image/png' ||
res.type == 'image/jpg' ||
res.type == 'application/msword' ||
type == 'docx'
) {
this.setState({slectedFile: res}, () => this.onSendWithImage());
} else {
alert(`${type} files not allowed`);
}
} catch (err) {
//Handling any exception (If any)
if (DocumentPicker.isCancel(err)) {
//If user canceled the document selection
// alert('Canceled from single doc picker');
} else {
//For Unknown Error
// alert('Unknown Error: ' + JSON.stringify(err));
throw err;
}
}
};
use this function when you want to send the image
onSendWithImage() {
let imageData = {
name: this.state.slectedFile.name,
type: this.state.slectedFile.type,
size: this.state.slectedFile.size,
uri: this.state.slectedFile.uri,
};
var formData = new FormData();
formData.append('type', 2);
formData.append('senderId', this.state.senderData.id),
formData.append('recieverId', this.state.reciverData._id),
formData.append('message', imageData);
post('sendMessage', formData).then(res =>
res.success ? this.msjSendSuccess(res) : this.msjSendFailure(res),
);
}
talk with your backend and say to him /her to send the image in the image key
complete enjoy React native

Vue js - not all the data showing after store dispatch

The select box not showing sometimes the first color and sometimes not showing the first color.
How can i make it to show all the item in the select box?
I'm not getting for some reason all the promises
You can see the issue in the picture
Please help me to fix this issue i'm new to vue js
My code:
data() {
return {
propertiesTree: []
}
}
getPropertyGroups(objectId: number): void {
if (this.$data.currentObjectId === objectId)
return;
let component: any = this;
this.$data.currentObjectId = objectId;
component.showLoader();
this.$store.dispatch('properties/getPropertyGroups', objectId)
.then(({ data, status }: { data: string | Array<propertiesInterfaces.PropertyGroupDto>, status: number }) => {
// console.log(data, "data");
// console.log(status, "status")
if (status === 500) {
this.$message({
message: data as string,
type: "error"
});
}
else {
let anyData = data as any;
anyData.map(item => {
item.properties.map(prop => {
if(prop.type.toString() === 'dictionary'){
prop.dictionaryList = [];
prop.color = '';
this.getWholeDictionaryList(prop.dictionaryId.value, prop)
}
});
});
}
component.hideLoader();
});
},
getWholeDictionaryList(dictionaryId: number, prop: any){
this.$store.dispatch('dictionaries/getWholeDictionaryList', dictionaryId).then(
({ data, status }: { data: Array<any> |string , status: number }) => {
if (status === 500) {
this.$message({
message: data as string,
type: "error"
});
} else {
const arrData = data as Array<any>;
arrData.map((item,index) => {
prop.dictionaryList = [];
prop.dictionaryList = data;
this.getDictionaryItemColor(item.id.value, data, index, prop);
});
}
});
},
getDictionaryItemColor(dictionaryItemId:number, dictionaryList: Array<any>, index:number, current){
this.$store.dispatch('patterns/getDictionaryItemColor', dictionaryItemId).then((data: any, status: number) => {
if (status === 500) {
this.$message({
message: data as string,
type: "error"
});
} else{
debugger
if(current.dictionaryItemId.value === data.data.sceneObjectId)
current.color = data.data.colorString;
dictionaryList[index].color = data.data.colorString ? data.data.colorString: '#FFFFFF';
}
});
},
Html code of the select box
<el-select v-model="data.color" placeholder="Select">
<el-option
v-for="item in data.dictionaryList"
:key="item.name"
:label="item.color"
:value="item.color">
</el-option>
</el-select>
I did return to dispatch
let dispatch = this.getWholeDictionaryList(prop.dictionaryId.value, prop)
let promiseArr = [];
promiseArr.push(dispatch);
after the map closing tag i did
Promise.all(promisArr).then( () => {
debugger
this.$data.propertiesTree = anyData;
});
And I've got it solved

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));
});
};
};

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