Vue 2 Laravel 5.3 Eloquent unable to retrieve data from object - eloquent

Vue2 has been reading eloquent pretty well so far for me but except this point where I struggle to debug.
Shop-show.vue
<template>
.....
.....
<div class="row">
{{shop.user.id}}
</div>
.....
.....
</template>
<script>
export default{
mounted(){
this.getShop()
},
methods:{
getShop(){
var vm = this
vm.$http.get('/getShop/'+vm.shopId).then((response)=>{
vm.shop = response.data.data.shop
})
},
.....
.....
}
</script>
ShopController.php
.....
.....
public function getShop($id)
{
$shop = Shop::where('id',$id)->with('user')->firstOrFail();
$response = [
'data' => [
'shop' => $shop
]
];
return response()->json($response);
}
.....
.....
web.php
Route::get('/getShop/{id}', 'ShopController#getShop');
here when I render {{shop.user}} in my template it gives me perfectly fine object of user including info such as id and name, however when I do {{shop.user.id}} or {{shop.user.name}} it console log errors as followings
error#1
[Vue warn]: Error when rendering component at
/Applications/XAMPP/xamppfiles/htdocs/soyegg/resources/assets/js/components/Shop/Shop-show.vue:
error#2
Uncaught TypeError: Cannot read property 'id' of undefined
at Proxy.render (eval at (app.js:335), :46:47)
at VueComponent.Vue._render (eval at (app.js:444), :3096:22)
at VueComponent.eval (eval at (app.js:444), :2464:21)
at Watcher.get (eval at (app.js:444), :1663:27)
at new Watcher (eval at (app.js:444), :1655:12)
at VueComponent.Vue._mount (eval at (app.js:444), :2463:19)
at VueComponent.Vue$3.$mount (eval at (app.js:444), :6104:15)
at VueComponent.Vue$3.$mount (eval at (app.js:444), :8494:16)
at init (eval at (app.js:444), :2777:11)
at createComponent (eval at (app.js:444), :4120:9)
this has never happened before, very weird. Please help.

As you are loading vm.shop from getShop method, which is an async method, you will not have anything in vm.shop till it is populated, so initially you will get this error.
To prevent this error, you can put a null check before using it, with the help of v-if, like following:
<template>
.....
.....
<div class="row" v-if="shop && shop.user">
{{shop.user.id}}
</div>
.....
.....
</template>

Related

Building error at #parcel/transformer-js "cannot access a scoped thread local variable without..."

I have a project with Parcel and Preact (to implement Algolia Autocomplete Search) and I suddenly got an error while npx parcel build theme/app-home.tsx --log-level verbose.
It worked before and I'm working with git but I can't found what changed to break the build.
The error:
Building app-home.tsx...
thread '<unnamed>' panicked at 'cannot access a scoped thread local variable without calling `set` first', /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/scoped-tls-1.0.0/src/lib.rs:168:9
🚨 Build failed.
#parcel/transformer-js: cannot access a scoped thread local variable without calling `set` first
Error: cannot access a scoped thread local variable without calling `set` first
at Object.transform (/Users/cozarkd/Documents/GitHub/projectX/node_modules/#parcel/transformer-js/lib/JSTransformer.js:365:31)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Transformation.runTransformer (/Users/cozarkd/Documents/GitHub/projectX/node_modules/#parcel/core/lib/Transformation.js:617:5)
at async Transformation.runPipeline (/Users/cozarkd/Documents/GitHub/projectX/node_modules/#parcel/core/lib/Transformation.js:366:36)
at async Transformation.runPipelines (/Users/cozarkd/Documents/GitHub/projectX/node_modules/#parcel/core/lib/Transformation.js:244:40)
at async Transformation.run (/Users/cozarkd/Documents/GitHub/projectX/node_modules/#parcel/core/lib/Transformation.js:170:19)
at async Child.handleRequest (/Users/cozarkd/Documents/GitHub/projectX/node_modules/#parcel/workers/lib/child.js:217:9)
The tsx file:
/** #jsx h */
import {
autocomplete,
AutocompleteComponents,
getAlgoliaResults,
} from '#algolia/autocomplete-js';
import algoliasearch from 'algoliasearch';
import { h, Fragment } from 'preact';
const appId = 'theappid';
const apiKey = 'theapikey';
const searchClient = algoliasearch(appId, apiKey);
/* const querySuggestionsPlugin = createQuerySuggestionsPlugin({
searchClient,
indexName: 'database_query_suggestions',
getSearchParams() {
return {
hitsPerPage: 5,
};
},
}); */
autocomplete({
// debug: true,
container: '#autocomplete',
placeholder: 'Escribe aquí, sin miedo',
openOnFocus: false,
defaultActiveItemId: 0,
autoFocus: true,
getSources({ query }) {
return [
{
sourceId: 'plantag',
getItemUrl({ item }) {
return item.url;
},
getItems() {
return getAlgoliaResults({
searchClient,
queries: [
{
indexName: 'database',
query,
params: {
hitsPerPage: 10,
clickAnalytics: true,
attributesToSnippet: [
'name:10',
'nombre'
],
snippetEllipsisText: '…',
},
},
],
});
},
templates: {
item({ item, components }) {
return <ProductItem hit={item} components={components} />;
},
noResults() {
return 'No hay plantas coincidentes :(';
},
},
},
];
},
// Default Navigator API implementation
navigator: {
navigate({ itemUrl }) {
window.location.assign(itemUrl);
},
navigateNewTab({ itemUrl }) {
const windowReference = window.open(itemUrl, '_blank', 'noopener');
if (windowReference) {
windowReference.focus();
}
},
navigateNewWindow({ itemUrl }) {
window.open(itemUrl, '_blank', 'noopener');
},
},
});
function ProductItem({ hit, components }: ProductItemProps) {
return (
<div className="c-single-result">
<a href={hit.url} className="aa-ItemLink">
<div className="l-flex-container">
<div className="aa-ItemContent">
<div className="aa-ItemContentBody">
<div className="aa-ItemContentTitle">
<components.Snippet hit={hit} attribute="nombre" />
</div>
</div>
<div className="aa-ItemContentSubtitle">
<components.Snippet hit={hit} attribute="name" />
</div>
<div className="aa-ItemActions">
<button
className="aa-ItemActionButton aa-DesktopOnly aa-ActiveOnly"
type="button"
title="Select"
style={{ pointerEvents: 'none' }}
>
<svg viewBox="0 0 30 27" width="30" height="27" fill="currentColor">
<path d="M10.0611 23.8881C10.6469 24.4606 10.6469 25.389 10.0611 25.9615C9.47533 26.5341 8.52558 26.5341 7.9398 25.9615L0.441103 18.632C0.4374 18.6284 0.433715 18.6248 0.430051 18.6211C0.164338 18.3566 0.000457764 17.994 0.000457764 17.594C0.000457764 17.3952 0.0409356 17.2056 0.114276 17.0328C0.187475 16.8598 0.295983 16.6978 0.439798 16.5572L7.9398 9.22642C8.52558 8.65385 9.47533 8.65385 10.0611 9.22642C10.6469 9.79899 10.6469 10.7273 10.0611 11.2999L5.12178 16.1278H13.5005C20.9565 16.1278 27.0005 10.2202 27.0005 2.93233V1.46616C27.0005 0.656424 27.672 -1.90735e-06 28.5005 -1.90735e-06C29.3289 -1.90735e-06 30.0005 0.656424 30.0005 1.46616V2.93233C30.0005 11.8397 22.6134 19.0602 13.5005 19.0602H5.12178L10.0611 23.8881Z"/>
</svg>
</button>
</div>
</div>
<div className="aa-ItemIcon aa-ItemIcon--picture aa-ItemIcon--alignTop">
<img src={hit.image} alt={hit.name} width="40" height="40" />
</div>
</div>
</a>
</div>
);
}
I can provide more info if needed. Did some search but I couldn't find anything related to Parcel with that error.
I'm able to repro the problem, and it looks like this might be a bug in parcel related to the JSX pragma at the top of the file (see github discussion here). If you remove this line, it should compile fine:
/** #jsx h */ <--delete this line.
Parcel will automatically detect which JSX pragma to use for your project based on finding preact as a dependency in package.json (see documentation). You can also manually control it with a tsconfig.json file like this:
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "preact"
}
}
(This bug should probably still be fixed, but hopefully this is enough to help you work around it. I filed a github issue here).

Property or method "info" is not defined on the instance but referenced during render

I'm trying to display information coming from a rest API with Vue.js
In a component I want to display users...
<template>
<div>
<h1>User Manager</h1>
<p>
{{ users }}
</p>
</div>
</template>
In the script part :
<script>
import {AxiosInstance as axios} from "axios";
export default {
name: "User",
data(){
return{
users: null
}
},
methods: {
getUsers(){
axios.get("http://localhost:4000/api/users").then(response => {
console.log(response);
this.users = response.data;
});
}
},
mounted(){
this.getUsers();
}
}
</script>
<style scoped></style>
I obtain unfortunatelly an error message such as :
Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"
TypeError: Cannot read property 'get' of undefined...

ReferenceError: " postIts.forEach(function(postit)" on list.ejs? postIts is not defined at eval (eval at compile

I need to loop through an object PostIts and display the "Id", " Title" with an ejs "forEach" Loop Am using sails.js "1.2.3" and mongodb on local host, but i get error
ReferenceError : postIts is not defined at eval (eval at compile ?
Here is the code on the PostItsController.js:
module.exports = {
list: function(req, res) {
// res.view('list');
PostIts.find({}).exec(function(err, postIts) {
if (err) {
res.send(500, { error: 'Database Error' });
}
res.view('list', { postIts: postIts });
});
}
};
And here is the code on list.ejs:
<tbody>
<% postIts.forEach(function(postit){ %>
<tr>
<td>
<%= postit.id %>
</td>
<td>
<%= postit.title %>
</td>
<td></td>
</tr>
<% }) %>
</tbody>
I should get the value of the ID and title displayed on the list.ejs page in a table, but instead I get an error that the postIts object is not defined.
First of all your route '/postIts/list': { view: 'list' }, should point to an action (since it has backend logic) not a view, so in your case "/postIts/list": "PostItsController.list", but if you're using actions2 things would be simpler
Secondly you don't need to tell your users that you have a database error error: "Database Error"
Using Actions2
sails generate action post/list
In your config/route.js
'POST /api/v1/post/list': { action: 'post/list' },
In your action
module.exports = {
friendlyName: "List Posts",
description: "List all post in our site",
inputs: {},
exits: {
success: {
description: "The path to your template file",
viewTemplatePath: "list"
}
},
fn: async function(inputs) {
var posts = await Post.find();
// All done.
return { postIts: posts };
}
};
postit works
An Boohoo! it works
https://sailsjs.com/documentation/concepts/actions-and-controllers/routing-to-actions
If you're sure that res.view('list', { postIts: postIts }); is actually sending the correct data you can use _.each(postIts, cb()) ... instead
For some reason the postIts object didnt save the data from the post req I made instead it just recalled what I posted. and I used the '_.each(postIts, function (postit)' and it finally worked.
to me its like a magic happened hahaha but yeah I learned from it.
thanks #Navicstein Rotciv for the quick replies.

SailsJS pass data to view - undefined

I'm playing about with SailsJS and I've got the following view:
<p>Products <%= category %></p>
With the following Controller:
module.exports = {
get: function(req, res) {
res.view('pages/products', {
category: req.params.category
});
}
};
And the route:
'/products/:category': 'ProductsController.get',
When navigating to this really simple setup, I get the following:
error: Sending 500 ("Server Error") response:
ReferenceError: /var/www/html/curioushaven/views/pages/products.ejs:1
>> 1| <p>Products <%= category %></p>
2|
category is not defined
at eval (eval at <anonymous> (/usr/lib/node_modules/sails/node_modules/ejs-locals/node_modules/ejs/lib/ejs.js:237:14), <anonymous>:30:54)
at eval (eval at <anonymous> (/usr/lib/node_modules/sails/node_modules/ejs-locals/node_modules/ejs/lib/ejs.js:237:14), <anonymous>:30:80)
at /usr/lib/node_modules/sails/node_modules/ejs-locals/node_modules/ejs/lib/ejs.js:250:15
at Object.exports.render (/usr/lib/node_modules/sails/node_modules/ejs-locals/node_modules/ejs/lib/ejs.js:288:13)
at Object.exports.renderFile (/usr/lib/node_modules/sails/node_modules/ejs-locals/node_modules/ejs/lib/ejs.js:318:20)
at SailsView.module.exports [as engine] (/usr/lib/node_modules/sails/node_modules/ejs-locals/index.js:85:7)
at SailsView.View.render (/usr/lib/node_modules/sails/node_modules/express/lib/view.js:76:8)
at Function.app.render (/usr/lib/node_modules/sails/node_modules/express/lib/application.js:561:10)
at ServerResponse.res.render (/usr/lib/node_modules/sails/node_modules/express/lib/response.js:845:7)
at ServerResponse.res.view (/usr/lib/node_modules/sails/lib/hooks/views/res.view.js:284:16)
at Object.module.exports.get (/var/www/html/curioushaven/api/controllers/ProductsController.js:10:7)
at wrapper (/usr/lib/node_modules/sails/node_modules/lodash/index.js:3095:19)
at routeTargetFnWrapper (/usr/lib/node_modules/sails/lib/router/bind.js:181:5)
at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:135:11)
at pass (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
at nextRoute (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:167:11)
at alwaysAllow (/usr/lib/node_modules/sails/lib/hooks/policies/index.js:224:11)
at routeTargetFnWrapper (/usr/lib/node_modules/sails/lib/router/bind.js:181:5)
at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
Can anyone explain what I'm doing wrong? Thanks!
Edit - I should point out that I've tried varying forms of req.param('category') and req.params.category etc etc...
Instead of using
req.param('category')
this
req.params.id
should fix your problem. However req.param('category') should work as well and from your code I cannot see why it should not work.

angular error : object has no method push

I am trying to make a angular work with a REST service and $resource.
it works to GET the datas from JSON, but when updating whith $save() or a custom method called $rec(), i have an error in the console saying : TypeError: Object #<c> has no method 'push'. Switching isArray to true or false, didn't change anything.
i made a plunker : http://plnkr.co/edit/fS2bjRKPgUulTbTxgg2j
the error is visible when you make it run on your own server.
the html:
<div ng-controller="TestCtrl">
<div ng-repeat="obj in objs">
<div>
<h3>{{obj.name}}</h3>
<h3>{{obj.age}}</h3>
<input type="text" ng-model="obj.name" /><br />
<input type="text" ng-model="obj.age" /><br />
<button ng-click="save(obj)">Save</button>
</div>
</div>
</div>
and the javascript:
'use strict';
angular.module('TestApp', ['TestApp.services', 'TestApp.controllers']);
angular.module('TestApp.services', ['ngResource']).
factory('Obj', function($resource){
return $resource('datas.json', {}, { 'rec': {method: 'POST', isArray: true } });
});
angular.module('TestApp.controllers', []).
controller('TestCtrl', ['$scope', 'Obj', function($scope, Obj) {
$scope.objs = Obj.query();
$scope.save = function(obj) {
obj.$save();
console.log(obj);
}
}]);
do you know where the error comes from ?
I have copied your plnkr to my dev machine, set up a sinatra site as below but I still do not see this error. the client posts a JSON string like {"name"=>"louise", "age"=>"32"} when I click on a blue button, and everything seems fine. Are you handling the POST appropriately?
here is my server code:
app.ru:
# -*- coding:utf-8; mode:ruby; -*-
require 'json'
require 'multi_json'
require 'sinatra/base'
require 'sinatra/json'
class App < Sinatra::Base
helpers Sinatra::JSON
get '/datas.json' do
json([
{"name" => "louise", "age" => "32"},
{"name" => "jeanne", "age" => "25"},
{"name" => "renée", "age" => "21"},
{"name" => "fernande", "age" => "28"}
])
end
post '/datas.json' do
data = JSON.parse request.body.read.to_s
200
end
end
config.ru:
# -*- coding:utf-8; mode:ruby; -*-
require './app.rb'
run App