Why is getter returning a proxy in Vuex 4 how do I access the actual data? [duplicate] - vue.js

I'm working with Laravel and Vue to make a single page web application. I've used Vue before to get the data from a database using a controller with no problem, but for some reason I'm now only getting a seemingly infinitely nested JS object that has getter and setter methods stored in each parent object instead of the data I queried. I've seen other people with similar issues, but the solutions that worked for them didn't work for me. For example, some people used JSON.parse(JSON.stringify(response.data)); to get just the raw data, but this doesn't work when I attempt to store it in this.actions. Here is my index method in my ActionLogController
public function index($url)
{
$companyName = explode("/", $url);
if(Auth::check())
{
$company = Company::where('name', '=', strtolower($companyName[count($companyName) - 1]))->first();
// If sortby not empty
$sortby = "created_at";
//assume desc (most recent)
$sortdirection = 'desc';
if(request()->has('sortdirection') && request()->sortdirection == 'asc')
{
$sortdirection = 'asc';
}
// if sortby is set
if(request()->has('sortby'))
{
$sortby = request()->sortby;
switch($sortby)
{
case "date":
$sortby = "string_date";
break;
case "company":
$sortby = "company_name";
break;
case "name":
// do nothing
break;
case "communication-type":
$sortby = "communication_type";
break;
case "contact":
// do nothing
break;
case "subject":
$sortby = "status";
break;
case "assigned-to":
$sortby = "assigned_to";
break;
case "action":
$sortby = "action_item";
break;
case "assigned-to":
$sortby = "assigned_to";
break;
default:
$sortby = 'created_at';
break;
}
}
}
if($sortdirection == 'asc') {
return Auth::user()->actionLogs
->where('activity_key', '=', '1,' . $company->id)
->sortBy($sortby);
}
return Auth::user()->actionLogs
->where('activity_key', '=', '1,' . $company->id)
->sortByDesc($sortby);
}
This is my Vue component to get the data from the controller. I know the template code works, because it worked fine when I sent it dummy data before pulling the data from the controller.
<style scoped>
.action-link {
cursor: pointer;
}
.m-b-none {
margin-bottom: 0;
}
</style>
<template>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th><a id="sortby-date" class="action-nav" href="?sortby=date&sortdirection=desc">Date</a></th>
<th><a id="sortby-company" class="action-nav" href="?sortby=company&sortdirection=desc">Company</a></th>
<th><a id="sortby-name" class="action-nav" href="?sortby=name&sortdirection=desc">Name</a></th>
<th><a id="sortby-communication-type" class="action-nav" href="?sortby=communication-type&sortdirection=desc">Communication Type</a></th>
<th><a id="sortby-contact" class="action-nav" href="?sortby=contact&sortdirection=desc">Contact</a></th>
<th><a id="sortby-subject" class="action-nav" href="?sortby=subject&sortdirection=desc">Subject</a></th>
<th><a id="sortby-action" class="action-nav" href="?sortby=action&sortdirection=desc">Comment/Action Item</a></th>
<th>Archive</th>
<!-- check if admin?? -->
<th><a id="sortby-assigned-to" class="action-nav" href="?sortby=date&sortdirection=desc">Assigned To</a></th>
<!-- /check if admin?? -->
</tr>
</thead>
<tbody v-if="actions.length > 0">
<tr v-for="action in actions">
<td>
{{ action.string_date }}
</td>
<td>
{{ action.company_name }}
</td>
<td>
{{ action.name }}
</td>
<td>
{{ action.communication_type }}
</td>
<td>
{{ action.contact }}
</td>
<td>
{{ action.status }}
</td>
<td>
{{ action.action_item }}
</td>
<td>
<input type="checkbox" :id="'archive-' + action.id" class="archive" :name="'archive-' + action.id">
</td>
<td :id="'record-' + action.id" class="assigned-to">
{{ action.assigned_to }}
</td>
</tr>
</tbody>
</table>
<p id="add-action" style="text-align: center;">
<button id="action-log-add" class="btn btn-sm btn-primary edit">Add Item</button>
<button id="action-log-edit" class="btn btn-sm btn-danger edit">Edit Items</button>
</p>
</div>
</template>
<script>
export default {
data() {
return {
actions: []
}
},
methods: {
getActionLogs(location) {
var company = location.split("/");
company = company[company.length - 1];
axios.get('/action-log/' + company)
.then(response => {
this.actions = response.data;
console.log(this.actions);
})
.catch(error => {
console.log('error! ' + error);
});
}
},
mounted() {
this.getActionLogs(window.location.href);
}
}
</script>
This is the output I get in the browser console
{…}
​
1: Getter & Setter
​
2: Getter & Setter
​
3: Getter & Setter
​
4: Getter & Setter
​
5: Getter & Setter
​
6: Getter & Setter
​
7: Getter & Setter
​
8: Getter & Setter
​
9: Getter & Setter
​
10: Getter & Setter
​
__ob__: Object { value: {…}, dep: {…}, vmCount: 0 }
​
<prototype>: Object { … }
I was expecting to see the normal array of data that gets returned, but this is what shows up instead and then won't update the component with the data. I'm new to Vue, so maybe there's something really easy I missing, but I can't seem to figure this out.

Writing up my comments above as a sort of canonical answer to this as it keeps coming up...
What you're looking at is how Vue proxies your data to make it reactive. This is because you're using console.log() on a Vue instance data property.
When you assign values to a data property, it is transformed to an observable so Vue can treat it reactively. I suggest you forget about trying to console.log() anything assigned to this and use the Vue Devtools browser extension to inspect your components and their data if you're having trouble rendering the response.
Please note, there is nothing wrong here.

Related

Strange behavior in Vue 3 without any error or warning

I have the following Vue 3 component that I am using in 2 pages that are setup like this in vue.config.js:
module.exports = {
// Put this in the ASP.NET Core directory
outputDir: "../wwwroot/app",
pages: {
vehicleDetails: "src/VehicleDetails.js",
driverDetails: "src/DriverDetails.js"
}
};
Both of these pages work and share the same underlying 'Certificates' component that looks like this:
<template>
<div>
<h3 id="Vue_Certificates">Certificates</h3>
<div>
objectId: {{objectId}} test
<table class="table table-striped table-hover table-condensed2" style="clear: both;">
<thead>
<tr>
<th><b>test</b></th>
<th style="text-align: right;">
<a href="#" #click="addCertificate">
<i class="fa fa-plus-square"></i> Add
</a>
</th>
</tr>
</thead>
<tbody>
<tr v-for="certificate in certificates" v-bind:key="certificate">
<td>{{ certificate.CertificateTypeId }}</td>
<td>
<a href="#" #click="removeCertificate(index)" title="Delete" style="float: right;" class="btn btn-default">
<i class="fa fa-trash"></i>
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import axios from 'axios';
import { onMounted, ref } from "vue";
import $ from 'jquery';
import _ from 'lodash';
export default {
components: {
},
props: {
objectId: String,
ownerIsVehicle: Boolean
},
data() {
return {
certificates: [],
types: []
}
},
created() {
const requestOne = axios.get("/api/v1.0/CertificateType/GetCertificateTypes");
const requestTwo = axios.get("/api/v1.0/Certificate/GetCertificateByObjectId", { params: { objectId: this.objectId, ownerIsVehicle: this.ownerIsVehicle } });
axios.all([requestOne, requestTwo]).then(axios.spread((...responses) => {
const responseOne = responses[0];
const responseTwo = responses[1];
alert("Axios calls completed 1");
this.types = responseOne.data;
var mappedData = responseTwo.data.map(x => ({
...x,
ValidFrom: new Date(x.ValidFrom),
ValidTill: new Date(x.ValidTill)
}));
this.certificates = mappedData;
alert("Axios calls completed 2");
console.log("succes");
})).catch(errors => {
console.log("fail");
});
},
methods: {
removeCertificate(index) {
this.certificates.splice(index, 1);
},
addCertificate() {
alert("Hello?");
}
}
}
</script>
The above code does NOT render the Vue component, but once I take out the two cells containing the anchors that call addCertificate & removeCertificate it all suddenly works.
For some reason I don't get any error in Chrome dev tools .. npm console .. visual studio console .. nowhere, so I have no clue at all what is going wrong.
Important: If I take out 1 of the 2 lines in vue.config.js it works on the page that is still added. The purpose of this component is that it can be reused.
FYI: I shrank down the code as much as possible to make sure other code bits aren't the cause.
For the record, the data property "certificates" was first a ref([]) but that doesn't seem to help at all.
Thanks in advance!

window.location.href in VUE 3 JS

I didn't get the issue here.
When I use
return window.location.href = 'https://www.google.com';
it works fine.
However, if I use my string variable. It doesn't work.Reloads back to page.
return window.location.href = this.navigationURL;
Full code:-
<table class="">
<tr
class="cursor-pointer"
v-for="currentView in authenticationMethodsAvailable"
:key="currentView.id"
>
<td class=""> (HERE)
**<button type= "button" #click="authenticationChoice(currentView['name'])" >**
<img
class="w-12 inline-block align-middle"
:src="showAuthenticationIcon(currentView['gitType'])"
/>
</button>
</td>
</tr>
</table>
The function being triggered
authenticationChoice(recieved) {
this.$store.state.gitSourceAuthenticationChoice = recieved;
this.$store.dispatch("gitSourceAuthenticationURL").then((response) => {
this.navigationURL = response["oauth2_redirect"];
console.log(this.navigationURL)
});
return this.navigationURL ;
// return window.location.href = String(this.navigationURL);
},
Remove the return which's breaking the code and move the code inside the then block as follows :
authenticationChoice(recieved) {
this.$store.state.gitSourceAuthenticationChoice = recieved;
this.$store.dispatch("gitSourceAuthenticationURL").then((response) => {
this.navigationURL = response["oauth2_redirect"];
console.log(this.navigationURL)
window.location.href = String(this.navigationURL);
});
},

Getting part of the page to display updated data in vue

I'm using vue to create a page where I list all users and if I click on the edit button the details of that user then gets shown
next to the list.
What I'm trying to do is, if I update a user and click save then the user details in the list needs to change.
The problem I'm having is that I'm not able to get the details to change in the list after I've saved.
My vue
<template>
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-7">
<table class="table table-striped table-sm mt-2">
<thead>
<tr>
<th>Name</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="user in displayAllUsers">
<td>{{ user.name }}</td>
<td>
<button class="btn btn-sm btn-success" #click="manageUser(user)">Edit</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-5" v-if="user != null">
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Manage {{ user.name }}</h4>
</div>
<div class="card-body">
<table class="table">
<tr>
<th>Name</th>
<td>
<input type="text" v-model="user.name">
</td>
</tr>
</table>
</div>
<div class="card-footer">
<button #click="updateUser()"class="btn btn-success"><i class="fa fa-save"></i> Save</button>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
components: {
},
data: function () {
return {
users: [],
user: null
}
},
computed: {
displayAllUsers(){
return this.users;
}
},
methods: {
manageUser(user){
axios.get('/admin/user/'+user.id).then((response) => {
this.user = response.data.user;
});
},
updateUser(){
axios.put('/admin/user/'+this.user.id, {
name: this.user.name
}).then((response) => {
this.users = response.data.user;
});
}
},
mounted() {
axios.get('/admin/users').then((response) => {
this.users = response.data.users;
});
}
}
</script>
There are two possible solutions.
The first is to run this code at the end of the updateUser method:
axios.get('/admin/users').then((response) => {
this.users = response.data.users;
});
The second is to use a state manager like Vuex.
The first scenario will fetch again your users data from the remote API and will update your view with all your users.
With the second scenario, you will handle your application state way much better than just using the data attribute of your page module, but in the background, it is more or less the same as the first solution I suggest.
To update the current user only in the table you could do something like that at the end of the updateUser method:
let userIdx = -1;
for(let idx = 0, l = this.users.length; idx < l; idx++) {
if ( this.user.id === this.users[idx].id ) {
userIdx = idx;
break;
}
}
if ( -1 !== userIdx ) {
this.users[userIdx] = this.user;
this.user = {};
}
Other than your problem, it seems like you don't need this code:
computed: {
displayAllUsers(){
return this.users;
}
},
You could remove this code, and instead use this code in the HTML part:
<tr v-for="user in users">
For your updateUser function you could just return the modified user in the same format that you have for all the users in you user list and update the user by index. This is presuming that the user you want to update is in the users array to start with.
updateUser() {
axios.put('/admin/user/'+this.user.id, {
name: this.user.name
}).then((response) => {
const updatedUser = response.data.user;
// Find the index of the updated user in the users list
const index = this.users.findIndex(user => user.id === updatedUser.id);
// If the user was found in the users list update it
if (index >= 0) {
// Use vue set to update the array by index and force an update on the page
this.$set(this.users, index, updatedUser);
}
});
}
This could be a good starting point.
Unrelated Note:
You can add your mounted function code to its own method, for example
getUsers() {
axios.get('/admin/users').then((response) => {
this.users = response.data.users;
});
}
then
mounted() {
this.getUsers()
}
this makes it a little cleaner and easier if you ever need to get the users again (example: if you start having filters the user can change)
As it could get more complex vuex would be a great addition.

V-model populated in a method not updating the DOM

I am newbie in VueJs.(vue 2). I have a problem here. I have a table where I am dynamically populating data like this.
<tbody>
<tr v-bind:key="queProduct.value" v-for="queProduct in queueProducts">
<td class="has-text-centered">
<figure class="image is-48x48">
<img :src="queProduct.image" alt="Placeholder image">
</figure>
</td>
<td><span>{{queProduct.title}}</span></td>
<td class="has-text-centered"><a class="has-text-link">
<span class="icon is-size-4" #click="openModalPopup(queProduct.id)">
<i class="fa fa-edit" />
</span>
</a>
</td>
<td class="has-text-centered"><a class="has-text-link">
<span class="icon is-size-4" #click="openModalPopup(queProduct.id)">
<img :src="queProduct.indicatorImg" />
</span>
</a>
</td>
<td class="has-text-centered"><a class="delete is-large has-background-link" #click="removeFromQueue(queProduct.id)"></a></td>
</tr>
</tbody>
methods:{
loadQueue(){
const indicators = store.get('productIndicators');
if(indicators === undefined){
store.set('productIndicators', []);
} else {
this.savedProprogressIndicators = indicators;
}
this.queueProducts.forEach(product => {
product.indicatorImg = indicatorImgBaseUrl +'Level-0.png';
this.savedProprogressIndicators.forEach(indicator => {
if(indicator.id === product.id){
product.indicatorImg = indicatorImgBaseUrl +indicator.image;
}
})
})
}
}
When I console.log the product, I see the product object being updated with the new value. But the dom isnt getting updated. Like,
this.product looks like this.
{
id: "d6dd8228-e0a6-4cb7-ab83-50ca5a937d45"
image: "https://zuomod.ca/image/cache/catalog/products/2018/Single/medium/50105-1-800x800.jpg"
inQueue: false
indicatorImg: "https://cdn.shopify.com/s/files/1/0003/9252/7936/files/Level-2.png"
saved: false
sku: "50105"
title: "Interstellar Ceiling Lamp"
}
But in the DOM, it looks like this
{
id: "d6dd8228-e0a6-4cb7-ab83-50ca5a937d45"
image: "https://zuomod.ca/image/cache/catalog/products/2018/Single/medium/50105-1-800x800.jpg"
inQueue: false
indicatorImg: "https://cdn.shopify.com/s/files/1/0003/9252/7936/files/Level-0.png"
saved: false
sku: "50105"
title: "Interstellar Ceiling Lamp"
}
Can you please help me resolve this?
Thanks,
Vandanaa
As you use Vuex, you should get your products directly from you store like in computed property in your vue definition. This will refresh the data directly from store without any action from vue side.
{
...
computed:{
...mapGetters({
queueProducts : 'queueProducts'
})
}
...
}
Furthermore, if your are using vuex, try to keep your logic inside your store. You vue should only display data.
Hava a look to vuex documentation to know when and where you should use
Getters, Mutations and Actions.
Hope this help.
this.queueProducts.forEach(product => {
...
...
...
}
this.$forceUpdate(); // Trying to add this code
I guessed your product.indicatorImg was not been watch by Vue, so it will not update the DOM. Trying to add this.$forceUpdate() in the end. It will force Vue to update DOM.

Calling a method into another method in vue

I'm trying to call a method from inside another method in vue.
What I get is an undefined in my console, but what I really want is the id that is called in the getId function
In a whole what I'm tring to do is use the addEvent function to get the checkbox events so that I can get a true or false from it and then send that to the saveCheckbox function and from the saveCheckbox function call the getId function to get the ID of that specific checkbox.
I hope I was able to explain it properly. If it's still unclear please let me know.
This is what I have
<template>
<div class="card-body">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Active</th>
<th scope="col">Title</th>
</tr>
</thead>
<tbody>
<tr v-for="(category, index) in categories" >
<td>
<input name="active" type="checkbox" v-model="category.active" #change="getId(category.id)" #click="addEvent">
</td>
<td>
{{ category.title }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: [
'attributes'
],
data(){
return {
categories: this.attributes,
}
},
methods: {
getId(id){
console.log(id);
return id
},
saveCheckbox(event){
console.log(this.getId());
},
addEvent ({ type, target }) {
const event = {
type,
isCheckbox: target.type === 'checkbox',
target: {
value: target.value,
checked: target.checked
}
}
this.saveCheckbox(event.target.checked)
}
},
mounted() {
console.log('Component mounted.')
}
}
</script>
You have to pass argument (Id) to getId method
Having a sort overview, you are not passing any Id to the method, and it trys to return that id. so maybe, that is what is not defined ?
The method calling is done well. with the this. keyword before it