vuesax put in vue api data table - vue.js

https://codepen.io/oxy1023/pen/gOKzbBL
methods: {
datas() {
var vm = this;
axios
.get(`http://115.145.177.104:1807/machinerepairhistory`, [
{
company: "",
factory: "",
repairno: "",
model_group: "",
repairdate: "",
repairtime: "",
repaircomp: "",
repairissue: "",
sparepart: "",
repairstory: "",
repairamt: "",
repairuserid: "",
repairusernm: "",
remark: "",
createdate: "",
createid: "",
updatedate: "",
updateid: "",
},
])
.then((response) => {
console.log("response.data : " + JSON.stringify(response.data));
vm.datas = response.data;
})
.catch((error) => {
console.error(error);
});
axios;
I have created a table using vuesax.
I want to insert data, but it doesn't come out properly. Why?
Is the data not entering properly in 'datas'?

Related

vue 3 watch specific object's item from array

I am working on nuxt 3 (vue 3) and I need to watch the particular item of the specific object from the array.
My array
const formData = reactive({
addressDetails: [
{
address: "",
street: "",
suburb: "",
state: "",
postCode: "",
country: "",
unitNumber: "",
streetNumber: "",
streetName: "",
timeAtaddressYears: "",
timeAtaddressMonths: "0",
},
]
});
Here, I want to watch if any timeAtaddressYears items value has changed but not on the whole formData.addressDetails value. Ex if I add new address details then no need to any watch but in specific address details if I change any address's timeAtaddressYears then watch should be called.
const formData = reactive({
addressDetails: [
{
address: "",
street: "",
suburb: "",
state: "",
postCode: "",
country: "",
unitNumber: "",
streetNumber: "",
streetName: "",
timeAtaddressYears: "",
timeAtaddressMonths: "0",
},
]
})
const selected = computed(() => {
return formData.addressDetails.map(form => form.timeAtaddressYears)
})
watch(selected, (newValue, oldValue) => {
console.log(newValue, oldValue)
})
You can try this:
watch(() => formData.addressDetails[0].address, (newValue, oldValue) => {
});
I have found a similar one, we need to add a deep watcher if we want to watch the particular item of the specific object from the array.
VueJS Deepwatchers
watch(
() => formData,
(newValue, oldValue) => {
console.log(newValue, oldValue);
},
{ deep: true });

set the new coordinates on the user after editing the address

I'm trying to edit the lat and lng on edit user. I manage to get the location displayed when I add a new user (I use getLocation() for both "add new user" and "edit user"), but the values of the lat and lng don't update when I run the edit function.
I tried to console.log the values and I do get the values of the user I'm editing in the console as well as the new coordinates but the user itself isn't updating.
any ideas?
(I use "vue-browser-geolocation")
export default {
....
name: "UsersBox",
data() {
return {
users: [],
// notEditing: true,
editingId: "",
showAddBox: false,
user: {
img: "janeth carton.jpg",
name: "",
role: "",
liveLocation: "Riviera State 32/106",
address1: "",
address2: "",
phone: "",
coordinates: {
lat: 0,
lng: 0,
},
},
};
},
async mounted() {
this.users = await this.fetchUsers();
},
methods: {
async saveEdit(userData) {
await this.getLocation(userData);
await fetch(`api/users/${userData.id}`, {
method: "PUT",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(userData),
})
.then((response) => response.json())
.then((userData) => console.log(userData));
this.editingId = "";
},
async getLocation(newUser) {
const API_KEY = "AIzaSyDkWzva7dAFQTO6rQVxZZawYTrcuo04PfI";
const API_URL = `https://maps.googleapis.com/maps/api/geocode/json?address=${newUser.address1}+${newUser.address2}&key=${API_KEY}`;
const apiResponse = await fetch(API_URL);
const locationData = await apiResponse.json();
console.log(locationData, "location");
console.log(locationData.results[0].geometry.location.lng, "lng");
console.log(locationData.results[0].geometry.location.lat, "lat");
console.log(this.user.coordinates.lat, "edit user lat");
this.user.coordinates.lat = locationData.results[0].geometry.location.lng;
this.user.coordinates.lng = locationData.results[0].geometry.location.lat;
},
....
},
};
</script>

like/dislike button with api call not working using vue an mongoDB

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

TypeError: $data.quotation.company is undefined

I have problem when I try to render data in my Vue3 application.
data() {
return {
quotation: [],
}
},
mounted() {
this.getQuotation()
},
methods: {
async getQuotation() {
this.$store.commit('setIsLoading', true)
const quotationID = this.$route.params.id
await axios
.get(`/api/v1/quotations/${quotationID}/`)
.then((response) => {
this.quotation = response.data
})
.catch(error => {
console.log(error)
})
},
}
The weird part is when I try to access {{quotation.company}} in template I can see the element of "company" without any error. The error TypeError: $data.quotation.company is undefined occurs when I get in depth {{quotation.company.name}} for example.
Axios is getting data like:
{
"id": 20,
"company": {
"id": 4,
"name": "xxxx",
"slug": "xxx",
"categories": [
{
"id": 7,
"name": "xxxx",
"slug": "xxxx"
}
],
"street2": "",
"postcode": 11111,
},
"home_type": "xxxx",
"Urgency": "",
"description": "xxxx",
}
I really don't understand :/
First the quotation property should be declared as an object like quotation: {}, then at the first rendering the field company is not available yet, so you need to add some conditional rendering as follows :
<div v-if="quotation.company" >
{{quotation.company.name}
</div>

Expo SQLite unable to query DB

I'm currently having a problem trying to query a DB in Expo SQLite.
In my app.js file I get the database from an external source like so:
// load DB for expo
FileSystem.downloadAsync(
'http://example.com/downloads/data.sqlite',
FileSystem.documentDirectory + 'data.sqlite'
)
.then(({ uri }) => {
console.log('Finished downloading to ', uri)
})
.catch(error => {
console.error(error);
});
I can confirm the database is downloaded in console I get:
Finished downloading to file:///var/mobile/Containers/Data/Application/6E1347A8-187E-4EF3-B360-60A0B24E1008/Documents/ExponentExperienceData/%2540anonymous%252Fexpo-sqlite-example-36a92625-6e95-41cc-af6d-a47fc254b237/data.sqlite
this is5507
I then load this in another component:
const db = SQLite.openDatabase('data.sqlite');
Then I run a query like so:
componentDidMount() {
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM dr_report_templates',
[],
(success) => console.log(success),
(error) => console.error(error)
);
})
}
I've confirmed that dr_report_templates is in the database.
The error I get is this:
h {
"_complete": false,
"_error": null,
"_running": true,
"_runningTimeout": false,
"_sqlQueue": t {
"first": undefined,
"last": undefined,
"length": 0,
},
"_websqlDatabase": h {
"_currentTask": _ {
"errorCallback": [Function anonymous],
"readOnly": false,
"successCallback": [Function anonymous],
"txnCallback": [Function anonymous],
},
"_db": n {
"_closed": false,
"_name": "data.sqlite",
},
"_running": true,
"_txnQueue": t {
"first": undefined,
"last": undefined,
"length": 0,
},
"version": "1.0",
},
}
In my device I get:
console.error: {"_websqlDatabase": {"version":"1.0","_db":...
Any ideas?
success and error callbacks take two parameters, first is a transaction and second is result/error