Duplicate data saving on MongoDB - reactjs

Hello I'm having a problem on my function save on my react project.
onSubmit={async (data, { setSubmitting, resetForm }) => {
for (var i = 0; i < selectedImageFiles.length; i++) {
const urlLink = await generateUploadUrl(selectedImageFiles[i].type);
const to_base64 = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
let blob = await to_base64(selectedImageFiles[i]);
let binary = atob(blob.split(",")[1]);
let array = [];
for (var x = 0; x < binary.length; x++) {
array.push(binary.charCodeAt(x));
}
let blobData = new Blob([new Uint8Array(array)], {
type: selectedImageFiles[i].type,
});
const uploadImageLink = await uploadImage(urlLink, blobData);
const newUploadImageLink = uploadImageLink.url.split("?")[0];
let productData = {
...data,
shopId: userShop._id,
images: selectedImageFiles,
category: collectCategoryId()[0],
};
addProduct(productData, userShop._id, newUploadImageLink).then(
(response) => {
if (response.status === 200) {
response.json().then((result) => {
setSubmitting(false); });
} else {
response.json().then((result) => {
setSubmitting(false);
});
}
}
);
}
}}
>
When I upload 2 files it also create 2 files on my database with same image link on both.
What I want is to create 1 data on database then the images.url must be different link from what I uploaded.
data number 1 that is inserted
{
"_id": {
"$oid": "62395b2faff15038acab7d0e"
},
"images": [{
"url": "https://devs.s3.ap-southeast-1.amazonaws.com/1647926063980.png",
}, {
"url": "https://devs.s3.ap-southeast-1.amazonaws.com/1647926063980.png",
}],
}
data number 2 that is inserted
{
"_id": {
"$oid": "62395b2faff15038acab7d0e"
},
"images": [{
"url": "https://devs.s3.ap-southeast-1.amazonaws.com/1647926063313.jpg",
}, {
"url": "https://devs.s3.ap-southeast-1.amazonaws.com/1647926063313.jpg",
}],
}
this is my addProduct
export const addProduct = async (productData, shopId, url) => {
const ls = new SecureLS({ encodingType: "aes" });
const token = ls.get("token");
const formdata = new FormData();
// console.log(productData.name);
for (let index = 0; index < productData.images.length; index++) {
formdata.append("file", productData.images[index]);
}
formdata.append("category", productData.category);
formdata.append("name", productData.name);
formdata.append("quantity", productData.quantity);
formdata.append("price", productData.price);
formdata.append("description", productData.description);
formdata.append("ingredients", productData.ingredients);
formdata.append("url", url);
return await fetch(`${API}/product/${shopId}`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
body: formdata,
})
.then((response) => {
return response;
})
.catch((err) => {
//console.log(err)
return err;
});
};

maybe something like this you need to be re debug and check addProduct last parameter :
onSubmit = async (data, { setSubmitting, resetForm }) => {
let filesUrls = [];
for (var i = 0; i < selectedImageFiles.length; i++) {
const urlLink = await generateUploadUrl(selectedImageFiles[i].type);
const to_base64 = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
let blob = await to_base64(selectedImageFiles[i]);
let binary = atob(blob.split(",")[1]);
let array = [];
for (var x = 0; x < binary.length; x++) {
array.push(binary.charCodeAt(x));
}
let blobData = new Blob([new Uint8Array(array)], {
type: selectedImageFiles[i].type,
});
const uploadImageLink = await uploadImage(urlLink, blobData);
const newUploadImageLink = uploadImageLink.url.split("?")[0];
filesUrls.push(newUploadImageLink);
}
let productData = {
...data,
shopId: userShop._id,
images: filesUrls,
category: collectCategoryId()[0],
};
addProduct(productData, userShop._id).then(
(response) => {
if (response.status === 200) {
response.json().then((result) => {
setSubmitting(false);
});
} else {
response.json().then((result) => {
setSubmitting(false);
});
}
});
}

Related

Store geolocation coordinates as a const variable react

im a little stuck. Im trying to store the user coordinates from the componentDidMount in the handlesubmit as a const however whenever i try to I'll get an error. The error i'm getting is :
'position' is not defined no-undef.
Any way i could go about storing the position as a const so i could access it in the handlesubmit part?
Thanks
Code is below
componentDidMount() {
navigator.geolocation.getCurrentPosition(function(pos ) {
const { latitude, longitude } = pos.coords;
console.log(pos )
console.log(latitude)
console.log(longitude)
});
}
handleSubmit = (event) => {
const pName = document.querySelector('#pName') .value.trim();
const pCondition = document.querySelector('#pCondition') .value.trim();
const pDescription = document.querySelector('#pDescription') .value.trim();
const pLocation = position
console.log(pLocation )
const post = 'pName=' + encodeURIComponent(pName) + '&pCondition=' + encodeURIComponent(pCondition) + '&pDescription=' + encodeURIComponent(pDescription);
alert('A form was submitted: ' + data);
fetch('api url', {
method: 'POST',
mode: "no-cors",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
// body: JSON.stringify(this.state)
body: post
}).then(function(response) {
console.log(response.text)
/*return response.json();*/
});
event.preventDefault();
}
Its simple
const getPosition = function () {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
}
getPosition()
.then(position => {
console.log(position);
sessionStorage.setItem('position', position);
)
.catch(error => {
console.error(error);
}
Use the variable position in the sessionStorage:
const data = sessionStorage.getItem('position');
Or you can use useState
const getPosition = function () {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
}
getPosition()
.then(position => {
console.log(position);
sessionStorage.setItem('position', position);
)
.catch(error => {
console.error(error);
}

expo convert from class to function

I am converting this code, which is working fine, from class to function. Replaced all of the classes to functions, created constant and useState as per many examples I have seen. There is no errors but it is not working and I can't figure out what is wrong. Any help is appreciated.
class App extends Component {
state = {
image: null,
uploading: false,
};
render() {
let {
image
} = this.state;
return (
...
);
}
_takePhoto = async () => {
const {
status: cameraPerm
} = await Permissions.askAsync(Permissions.CAMERA);
const {
status: cameraRollPerm
} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera AND camera roll
if (cameraPerm === 'granted' && cameraRollPerm === 'granted') {
let pickerResult = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: false,
aspect: [4, 3],
quality: 0.2,
});
this._handleImagePicked(pickerResult);
}
};
_handleImagePicked = async pickerResult => {
let uploadResponse, uploadResult;
try {
this.setState({
uploading: true
});
if (!pickerResult.cancelled) {
uploadResponse = await uploadImageAsync(pickerResult.uri);
uploadResult = await uploadResponse.json();
this.setState({
image: uploadResult.location
});
}
} catch (e) {
console.log({ uploadResponse });
console.log({ uploadResult });
console.log({ e });
alert('Upload failed, sorry :(');
} finally {
this.setState({
uploading: false
});
}
};
}
async function uploadImageAsync(uri) {
let apiUrl = 'http://elieatme.com/kamel/uploads.php';
let uriParts = uri.split('.');
let fileType = uriParts[uriParts.length - 1];
var datetime = moment()
.utcOffset('+02:00')
.format('YYYY-MM-DD hh:mm:ss a');
let formData = new FormData();
formData.append('fileToUpload', {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
};
return fetch(apiUrl, options);
}
export default App;
to function code below
function App() {
const [image, setImage] = useState(null);
const [uploading, setUploading] = useState(false);
let pickerResult;
return (
...
);
function _takePhoto() {
const {
status: cameraPerm
} = Permissions.askAsync(Permissions.CAMERA);
const {
status: cameraRollPerm
} = Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera AND camera roll
if (cameraPerm === 'granted' && cameraRollPerm === 'granted') {
pickerResult = ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: false,
aspect: [4, 3],
quality: 0.2,
});
_handleImagePicked(pickerResult);
}
}
function _handleImagePicked() {
let uploadResponse, uploadResult;
try {
setUploading(true);
if (!pickerResult.cancelled) {
uploadResponse = uploadImageAsync(pickerResult.uri);
uploadResult = uploadResponse.json();
setImage(uploadResult.location);
}
} catch (e) {
console.log({ uploadResponse });
console.log({ uploadResult });
console.log({ e });
alert('Upload failed, sorry :(');
} finally {
setUploading(false);
}
}
}
function uploadImageAsync(uri) {
let apiUrl = 'http://elieatme.com/kamel/uploads.php';
let uriParts = uri.split('.');
let fileType = uriParts[uriParts.length - 1];
var datetime = moment()
.utcOffset('+02:00')
.format('YYYY-MM-DD hh:mm:ss a');
let formData = new FormData();
formData.append('fileToUpload', {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
};
return fetch(apiUrl, options);
}
export default App;
Please check where you have closed your function app.
You have closed your app function after _handleImagePicked().
And after return statement none of you code going to execute.
function App() {
const [image, setImage] = useState(null);
const [uploading, setUploading] = useState(false);
let pickerResult;
return (
...
);
} /// Close app function
function _takePhoto() {
const {
status: cameraPerm
} = Permissions.askAsync(Permissions.CAMERA);
const {
status: cameraRollPerm
} = Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera AND camera roll
if (cameraPerm === 'granted' && cameraRollPerm === 'granted') {
pickerResult = ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: false,
aspect: [4, 3],
quality: 0.2,
});
_handleImagePicked(pickerResult);
}
}
function _handleImagePicked() {
let uploadResponse, uploadResult;
try {
setUploading(true);
if (!pickerResult.cancelled) {
uploadResponse = uploadImageAsync(pickerResult.uri);
uploadResult = uploadResponse.json();
setImage(uploadResult.location);
}
} catch (e) {
console.log({ uploadResponse });
console.log({ uploadResult });
console.log({ e });
alert('Upload failed, sorry :(');
} finally {
setUploading(false);
}
}
}/// Remove this closing
function uploadImageAsync(uri) {
let apiUrl = 'http://elieatme.com/kamel/uploads.php';
let uriParts = uri.split('.');
let fileType = uriParts[uriParts.length - 1];
var datetime = moment()
.utcOffset('+02:00')
.format('YYYY-MM-DD hh:mm:ss a');
let formData = new FormData();
formData.append('fileToUpload', {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
};
return fetch(apiUrl, options);
}
export default App;

React Hook , setvariable and print in same useeffect

I want to set name,room variable after axios calling and before socket.join. But SetName() is not working properly, and socket.join() is not receiving new value of Name, Room.
Name and Room value of set after socket.join() is completed, but I wanted is to set Name and Room value before socket.join()
useEffect(() => {
(async () => {
const response = await axios({
method: "get",
url: "https://localhost:5000/",
mode: "cors",
withCredentials: true,
});
const data = await response.data;
await condition_check();
await soc();
function condition_check() {
return new Promise(async (resolve) => {
if (location.state === undefined) {
SetConnected(true);
SetValid(false);
}
if (data.status === "ok" && location.state !== undefined) {
SetName(location.state.Name, () => {
console.log(name);
});
SetRoom(location.state.Room);
SetUserId(location.state.UserId);
SetValid(true);
resolve(console.log("1", name, room));
SetConnected(true);
SetSetup(true);
}
});
}
function soc() {
return new Promise((resolve) => {
if (setup === true) {
socket = socketIOClient.connect(ENDPOINT);
socket.emit(
"Join",
{ Name: name, Room: room, UserId: userid },
(err) => {
if (err) {
alert(err);
}
}
);
console.log("2", name, room);
socket.on("message", ({ Name, Room, message, currenttime }) => {
setMessages((messages) => [...messages, message]);
setSenders((senders) => [...senders, Name]);
setTime((time) => [...time, currenttime]);
resolve(console.log(currenttime));
});
}
});
}
})();
// because `SetRoom` `SetName` is async
useEffect(() => {
(async () => {
const response = await axios({
method: "get",
url: "https://localhost:5000/",
mode: "cors",
withCredentials: true,
});
const data = await response.data;
let NAME;
let ROOM;
await condition_check();
await soc();
function condition_check() {
return new Promise(async (resolve) => {
if (location.state === undefined) {
SetConnected(true);
SetValid(false);
}
if (data.status === "ok" && location.state !== undefined) {
...
NAME = location.state.Name
ROOM = location.state.Room
...
}
});
}
function soc() {
// use local variable `ROOM` and `NAME`
return new Promise((resolve) => {
...
});
}
})();

Using the state hook to count inside of promises

I am back with a newbie question, eventually i have built a function too complex with my promises, but maybe someone has some insight in why the setSiteAdded/Updated and setArticlesAdded/Updated functions are not working in the correct way for me here. I want to count up, all directly saved and updated elements of the fetched data from my API.
I am using typeORM locally on my ios device with sqlite.
Here is my code:
const saveToDB = (type, element) => {
return new Promise(async (resolve, reject) => {
if (type === 'site') {
let site = new Site();
site.created = element.CREATED;
site.sitenum = element.SITENUM;
site.title = element.TITLE;
site.updated = element.UPDATED;
let siteRepository = getRepository(Site);
siteRepository.findOne({ where: { sitenum: site.sitenum } })
.then((foundSite) => {
site.id = foundSite.id;
if (foundSite.updated !== site.updated) {
siteRepository.update(foundSite.id, site)
.then((savedSite) => {
console.log("Site has been updated!", savedSite);
setSitesUpdated(sitesUpdated + 1);
resolve(savedSite);
}).catch((error) => {
console.log("Error: ", error);
reject();
});
} else {
resolve();
}
})
.catch(() => {
siteRepository.save(site)
.then((savedSite) => {
console.log("Site has been saved!", savedSite);
setSitesAdded(sitesAdded + 1);
resolve(savedSite);
})
.catch((error) => {
console.log("Error: ", error);
reject();
});
});
} else if (type === 'article') {
let article = new Article();
article.created = element.CREATED;
article.updated = element.UPDATED;
article.artnum = element.ARTNUM;
article.ean = element.EAN;
article.title1 = element.TITLE1;
article.title2 = element.TITLE2;
article.unit = element.UNIT;
article.price = element.PRICE;
article.quantity = element.QUANTITY;
let articleRepository = getRepository(Article);
articleRepository.findOne({ where: { artnum: article.artnum } })
.then((foundArticle) => {
article.id = foundArticle.id;
if (foundArticle.updated !== article.updated) {
articleRepository.update(foundArticle.id, article)
.then((savedArticle) => {
console.log("Article has been updated!", savedArticle);
setArticlesUpdated(articlesUpdated + 1);
resolve(savedArticle);
})
.catch((error) => {
console.log("Error: ", error);
reject();
});
} else {
resolve();
}
})
.catch(() => {
articleRepository.save(article)
.then((savedArticle) => {
console.log("Article has been saved!", savedArticle);
setArticlesAdded(articlesAdded + 1);
resolve(savedArticle);
})
.catch((error) => {
console.log("Error: ", error);
reject();
});
});
}
})
}
const fetchDataFromServer = () => {
return new Promise(async (resolve, reject) => {
setLoading(true);
Promise.all([
new Promise(async (resolve, reject) => {
try {
let counter = 0;
let sites = await fetch(
host + 'sites', { method: 'GET', headers: { token: token } }
)
let sitesJson = await sites.json();
Promise.all(sitesJson.data.map(async (element) => {
counter++;
return saveToDB('site', element)
}))
.then(() => {
setSitesAdded(counter);
resolve();
})
.catch(() => reject());
} catch (error) {
console.error(error);
}
}),
new Promise(async (resolve, reject) => {
try {
let articles = await fetch(
host + 'articles', { method: 'GET', headers: { token: token } }
)
let articlesJson = await articles.json();
Promise.all(articlesJson.data.map(async (element) => {
return saveToDB('article', element)
}))
.then(() => resolve())
.catch(() => reject());
} catch (error) {
console.error(error);
}
})
])
.then(() => resolve())
.catch(() => reject())
})
}

Picking up document/Images from mobile device and show them into a list in react native

I am using react native document picker library to upload documents to the server my code is working perfectly but the issue is i want to show list of these selected images/documents i am not sure how to perform that action here is my code....
Document Selection code:
pickMultiple() {
try {
DocumentPicker.pickMultiple({
})
.then(images => {
this.setState({
image: null,
images: images
});
//console.log(images.length);
})
.catch(e => alert(e));
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}
}
Form Uploading code:
SubmitProposal = async () => {
const Uid = await AsyncStorage.getItem("projectUid");
const { params } = this.props.navigation.state;
const { amount, Description, DurationListKnown, images } = this.state;
console.log(
amount,
Description,
DurationListKnown[0],
images,
params.job_id,
images.length,
Uid
);
const formData = new FormData();
formData.append('user_id' , Uid);
formData.append('project_id' , params.job_id);
formData.append('proposed_amount' , amount);
formData.append('proposed_time' , DurationListKnown[0]);
formData.append('proposed_content' , Description);
formData.append('size' , images.length);
//formData.append('proposal_files' , images);
images.forEach((item, i) => {
// propertyData.description = this.props.description
var path = item.uri;
// var filename = path.substring(path.lastIndexOf('/')+1);
var filename = item.name;
formData.append("proposal_files"+i, {
uri: path,
type: item.type,
name: filename || `filename${i}.jpg`,
});
});
console.log(formData);
fetch('https://...proposal/add_proposal',{
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
}).then(response => {
if (response.status == "200") {
console.log(response);
this.showSuccessAlert();
} else if (response.status == "203") {
console.log(response);
this.showAlert();
}
}).catch((error) => {
console.log(JSON.stringify( error));
});
};
kindly help me about how can i show list of these images/documents

Resources