How to notifiy the user on success the file write.
RNFetchBlob.fs.writeFile(path, Base64Code[1], 'base64')
.then(res => {
console.log(res);
if (res > 0) {
alert('download_success');
} else {
alert('download_failed');
}
});
You can try using a local notification with react-native-push-notification
Here's how you can do it:
first of all, import the library
import PushNotification from 'react-native-push-notification'
and then, the function itself:
RNFetchBlob.fs.writeFile(path, Base64Code[1], 'base64')
.then(res => {
console.log(res);
if (res > 0) {
PushNotification.localNotification({
id: '69',
ticker: "Download sucess!",
autoCancel: true,
vibrate: true,
vibration: 300,
ongoing: false,
priority: "high",
visibility: "private",
importance: "high",
title: "My app name",
message: "Your file has now ben saved!"
});
} else {
PushNotification.localNotification({
id: '69',
ticker: "Download error!",
autoCancel: true,
vibrate: true,
vibration: 300,
ongoing: false,
priority: "high",
visibility: "private",
importance: "high",
title: "My app name",
message: "Errors ocurred while saving the file!"
});
}
});
RNFetchBlob.fs
.writeFile(pathToWrite, data, 'utf8')
.then(() => {
RNFetchBlob.android.addCompleteDownload({
title: 'data.pdf',
description: 'Download complete',
mime: 'application/pdf',
path: pathToWrite,
showNotification: true,
});
console.log(`wrote file ${pathToWrite}`);
})
.catch((error) => console.error(error));
Related
I am learning vuejs and i am working on my first project which is a social network, and i want to implement a like button that call the api to add a like or remove it if the user has already liked it. It does work in my backend but i can't make it work in the front.
I need to send the userId and add or remove the like when i click on the button
This is the data
data() {
return {
post: {
file: "",
content: "",
likes: 0,
},
showModal: false,
showModifyPost: false,
user: {
firstname: "",
lastname: "",
_id: "",
},
};
},
the last method i tried
likePost(id) {
axios
.post('http://127.0.0.1:3000/api/post/like/' + id, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then(() => {
console.log("response", response);
this.user._id = response.data._id;
if(post.usersLiked == user._id) {
this.post.likes += 0
} else if (post.usersLiked != user._id) {
this.post.likes += 1
};
})
.catch((error) => console.log(error));
}
and this is the model
const postSchema = mongoose.Schema({
userId: { type: String, required: true, ref: "User" },
content: { type: String, required: true, trim: true },
imageUrl: { type: String, trim: true },
likes: { type: Number, default: 0 },
usersLiked: [{ type: String, ref: "User" }],
firstname: {type: String, required: true, trim: true },
lastname: {type: String, required: true, trim: true },
created_at: { type: Date},
updated_at: { type: Date }
});
Any idea what is wrong ? Thank you !
.then(() => { // you missed value response from Promise here
this.user._id = response.data._id;
if(post.usersLiked == user._id)
})
Do you mean this.post.usersLiked === user._id I suppose, so post within your data options should be
post: {
file: "",
content: "",
likes: 0,
usersLiked: false,
// something else reflect to your post schema
},
i want to implement a like button that call the api to add a like or remove it if the user has already liked it
By saying that you just need a simple boolean value to do this
likePost(id) {
axios
.post('http://127.0.0.1:3000/api/post/like/' + id, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then((response) => {
// Just need to toggle state
this.$set(this.post, 'usersLiked', this.post.usersLiked !== response?.data?._id)
})
.catch((error) => console.log(error));
}
Found the answer, i changed the axios method to this
likePost(id) {
let userId = localStorage.getItem('userId');
axios
.post('http://127.0.0.1:3000/api/post/like/' + id, { userId }, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then((response) => {
console.log(response.data);
this.getAllPost();
})
.catch((error) => console.log(error));
}
i also made a few changes to the data
data() {
return {
posts: [],
post: {
file: "",
content: "",
},
showModal: false,
showModifyPost: false,
user: {
firstname: "",
lastname: "",
_id: "",
},
};
},
and i also made some changes on the controller
exports.ratePost = (req, res, next) => {
console.log(req.body.userId)
//using findOne function to find the post
Post.findOne({ _id: req.params.id }).then(post => {
if (!post.usersLiked.includes(req.body.userId)) {
// making a object with $inc and $push methods to add a like and to add the user's id
let toChange = {
$inc: { likes: +1 },
$push: { usersLiked: req.body.userId },
};
// we update the result for the like
Post.updateOne({ _id: req.params.id }, toChange)
// then we send the result and the message
.then(post =>
res
.status(200)
.json(
{ message: "Liked !", data: post }
)
)
.catch(error => res.status(400).json({ error }));
} else if (post.usersLiked.includes(req.body.userId)) {
// using the updateOne function to update the result
Post.updateOne(
{ _id: req.params.id },
// we use a pull method to take off a like
{ $pull: { usersLiked: req.body.userId }, $inc: { likes: -1 } }
)
.then(post => {
// then we send the result and the message
res
.status(200)
.json(
{ message: "Post unliked", data: post }
);
})
.catch(error => res.status(400).json({ error }));
}
});
};
Error: WARN No channel id passed, notifications may not work.
[LOG] createChannel returned 'false'
How to pass the channel id ?
Here's my code:
export const LocalNotification = () => {
PushNotification.localNotification({
autoCancel: true,
bigText:
'This is local notification demo in React Native app. Only shown, when expanded.',
subText: 'Local Notification Demo',
title: 'Local Notification Title',
message: 'Expand me to see more',
vibrate: true,
vibration: 300,
playSound: true,
soundName: 'default',
actions: '["Yes", "No"]'
})
}
const startFunction = async () => {
PushNotification.createChannel(
{
channelId: "channel-id-1",
channelName: "My channel",
channelDescription: "A channel to categorise your notifications",
playSound: false,
soundName: "default",
importance: Importance.HIGH,
vibrate: true,
},
(created) => console.log(`createChannel returned '${created}'`)
);
LocalNotification();
}
PushNotification.createChannel(
{
channelId: "channel-id-1",
channelName: "My channel",
channelDescription: "A channel to categorise your notifications",
playSound: false,
soundName: "default",
vibrate: true,
},
(created) => console.log(`createChannel returned '${created}'`)
);
PushNotification.localNotification({
channelId : "channel-id-1",// this is where you need to add local notification
autoCancel: true,
bigText:
'This is local notification demo in React Native app. Only shown, when expanded.',
subText: 'Local Notification Demo',
title: 'Local Notification Title',
message: 'Expand me to see more',
vibrate: true,
vibration: 300,
playSound: true,
soundName: 'default',
actions: '["Yes", "No"]'
})
i want to integrate this toast only if axios post is executed. i placed it like that and it's shown up even if my post axios function is not working.
how can i fix that ?
My code:
methods: {
addRinvoice: function () {
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
axios.post('/addrinvoice', this.rinvoice)
.then(response => {
toast({
type: 'success',
title: 'Invoice added in Database'
}),
console.log(response.data);
if (response.data.etat) {
this.rinvoice = {
id: 0,
amount: response.data.etat.amount,
};}})
.catch(error => {
console.log('errors: ', error)
}) },
Just put your call invoking the toast method inside your then() method:
methods: {
addRinvoice: function () {
axios.post('/addrinvoice', this.rinvoice)
.then(response => {
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
toast({
type: 'success',
title: 'Invoice added in Database'
}),
console.log(response.data);
if (response.data.etat) {
this.rinvoice = {
id: 0,
amount: response.data.etat.amount,
};}})
.catch(error => {
console.log('errors: ', error)
})
},
place it inside then after getting response successfully like :
then(response=>{
...
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
toast({
type: 'success',
title: 'Invoice added in Database'
}
}
I am just trying to get a simple demo app working using webpack and devextreme components. I built the app first without webpack and it all worked fine. I am now trying to refactor it to use webpack. I can't get the dataGrid page to work I am just getting a console error .dxDataGrid is not a function. If anyone can see where I have gone wrong any ideas would be great.
var $ = require('jquery');
var ko = require('knockout');
require('devextreme/integration/knockout');
require('devextreme/ui/data_grid');
require('devextreme/ui/form');
require('devextreme/ui/text_box');
require('devextreme/ui/button');
require('devextreme/ui/check_box');
require('devextreme/ui/popup');
var AspNetData = require('devextreme-aspnet-data/js/dx.aspnet.data');
$(function () {
var url = CONST_URL + 'Login/';
$("#userGrid").dxDataGrid({
showColumnLines: false,
showRowLines: true,
rowAlternationEnabled: true,
columnHidingEnabled: true,
showBorders: true,
dataSource: AspNetData.createStore({
key: "id",
loadUrl: url + "GetUsers",
insertUrl: url + "UpsertUser",
updateUrl: url + "UpsertUser",
deleteUrl: url + "DeleteUser"
}),
columnChooser: {
//enabled: true,
//mode: "select"
},
paging: {
pageSize: 5
},
pager: {
showPageSizeSelector: true,
//allowedPageSizes: [5, 10, 15],
showInfo: true
},
editing: {
allowUpdating: true,
mode: "form",
allowAdding: true,
allowDeleting: true
},
columns: [
{
dataField: "id",
caption: "User ID",
formItem: {
visible: false
},
hidingPriority: 1
},
{
dataField: "username",
caption: "Username",
validationRules: [{
type: "required",
message: "Username"
}, {
type: 'pattern',
pattern: /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/,
message: 'Please supply a valid email address.'
}],
formItem: {
visible: true
},
hidingPriority: 3
},
{
dataField: "password",
caption: "password",
mode: "password",
validationRules: [{
type: "required",
message: "Password",
}, {
type: "stringLength",
min: 8,
message: "Your password must have at least 8 characters."
}],
visible: false,
formItem: {
visible: true
}
},
{
dataField: "date_created",
caption: "Date Created",
formItem: {
visible: false
},
hidingPriority: 2
},
{
dataField: "is_locked",
caption: "User Locked Out",
hidingPriority: 0
}],
onEditorPreparing: function (e) {
if (e.dataField === "password") {
e.editorOptions.mode = 'password';
}
if (e.parentType === "dataRow" && e.dataField === "username") {
setTimeout(function () { $(e.editorElement).dxTextBox("focus") }, 100);
}
},
onToolbarPreparing: function (e) {
var dataGrid = e.component;
e.toolbarOptions.items.unshift({
location: "before",
template: function () {
return $("<div/>")
.append(
$("<h2 />")
.text("User List")
);
}
});
},
onEditingStart: function (e) {
isUpdateCanceled = false;
e.component.columnOption("date_created", "allowEditing", false);
e.component.columnOption("id", "allowEditing", false);
},
onInitNewRow: function (e) {
isUpdateCanceled = false;
e.component.columnOption("date_created", "allowEditing", false);
e.component.columnOption("id", "allowEditing", false);
e.component.columnOption("is_locked", "allowEditing", false);
},
onContentReady: function (e) {
var saveButton = $(".dx-button[aria-label='Save']");
if (saveButton.length > 0)
saveButton.click(function (event) {
console.log(e.component);
if (!isUpdateCanceled) {
upsert(e.component);
event.stopPropagation();
}
});
}
});
});
Devexpress team gave me the solution. I thought I would post it here in case anyone else has the same issue. I was missing the jquery intergration.
require('devextreme/integration/jquery');
I have the following swal code and it works fine if the returned status for the HTTP call is '200'. But if I get a '403' unauthorized error the swal loader keeps spinning and the message never goes away, like shown below. I'm not sure if I'm not handling the error correctly.
Can you help?
let that = this;
swal({
title: 'Are you sure?',
text: 'You won\'t be able to revert this!',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
confirmButtonColor: '#d33',
cancelButtonText: 'No, keep it',
showLoaderOnConfirm: true,
preConfirm: function (email) {
return new Promise(function (resolve, reject) {
that.http.get(url, {"headers": headers})
.map(res => res)
.subscribe(data => {
console.log(data);
if (data.status === 200) {
resolve();
} else {
reject(data.status);
}
})
})
},
allowOutsideClick: false
}).then(function() {
swal(
'Deleted!',
'The user has been deleted.',
'success'
)
}, function(dismiss) {
if (dismiss === 'cancel') {
swal(
'Cancelled',
'Nothing has been deleted!',
'error'
)
}
}).catch((error) => {
console.log('error_does_not_reach_here', error);
})
This is a example of my code:
swal({
title: "Confirm",
text: "¿Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonText: 'Aceptar',
cancelButtonText: 'Cancelar'
}).then(function () {
//If Press ok, send the data
var arr = {
cuil: empDP.fd.Cuil,
cct: empDP.fd.Cct,
activity: empDP.fd.Activity,
};
Vue.http.post(empDP.globalurl + "/persondata/save", arr).then(function (response) {
swal('Data saved correctly', '', 'success');
empDP.clean();
}, function (response) {
//If Response return error
swal('Show a Text Error', '', 'error');
});