Infinit loop with axios call - node.js

I have a problem to loading data with API call with axios, I have an infinit loop when the method loadTasks() is called.
I want to load todo list, and load associated tasks inside. Maybe I'm using the wrong way.
Here my template with Todo liste v-for loop and inside an another v-loop lo display Task list associated, loaded with loadTasks(list.id).
<template >
<div class="todo-list-container">
<div class="list flex flex-col max-w-sm mx-auto">
<hr class="text-gray1 mb-4">
<div v-for="list in allTodoList" :value="list.id" :key="list.id" class="mb-4 px-4 py-2 bg-gray-dark rounded-xl ">
<div class="flex items-center gap-4 mb-4">
<div class="date text-sm text text-left text-gray1">{{ list.order }}</div>
<div class="title font-bold">{{ list.title }}</div>
<div class="ml-auto font-bold text-right">
<button v-if="list.id" #click="this.$store.dispatch('removeTodoList', list.id)">Supprimer</button>
</div>
</div>
<div class="task-container">
{{loadTasks(list.id)}}
<div v-if="loading">loading...</div>
<div v-if="tasks" class="list weekList flex flex-col p-6 max-w-sm mx-auto bg-gray rounded-xl shadow-lg">
<div class="flex flex-row gap-4">
Liste des taches <button #click="displayForm(list.id)" href="#" class="px-2 rounded bg-blue text-white text-sm uppercase right">+</button>
<hr class="text-gray1 mb-4">
</div>
<div v-for="task in tasks" :value="task.id" :key="task.id" class=" mb-4 flex items-center gap-4 flex-row">
<div class="date text-sm text text-left text-gray1">{{ task.position }}</div>
<div class="">
<div class="title font-bold">{{ task.title }}</div>
<div class="date text-sm text text-left text-gray1">Terminé <input type="checkbox" name="finish" id="" :checked="task.finish" ></div>
</div>
<div class="ml-auto font-bold text-right">
<button v-if="task.id" #click="this.$store.dispatch('removeTask', task.id)">Supprimer</button>
</div>
</div>
</div>
</div>
</div>
{{this.$store.state.error}}
<div :class="[ showForm === true ? '' : 'hidden' ] + ' addNewForm'">
<add-task-form :listId="getListId" :showForm="showForm" ></add-task-form>
</div>
</div>
</div>
</template>
Script:
<script>
import addTaskForm from './addTaskForm.vue';
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3000';
export default {
name: 'todoList',
props: ['allTodoList'],
components: {
addTaskForm,
},
data() {
return {
loading: false,
visibleForm: false,
listId: 0,
tasks: [],
};
},
methods: {
displayForm(listId) {
this.listId = listId;
this.visibleForm = !this.visibleForm;
},
async loadTasks(listId) {
try {
if(!listId) { return; }
const tasksList = await axios.get(`/list/${listId}/tasks`);
if (!tasksList.data.tasks || !tasksList.data.tasks.length) {
return;
}
else {
this.tasks = tasksList.data.tasks
}
} catch (error) {
this.$store.dispatch('setError', error);
}
},
cancelForm() {
this.visibleForm = false;
},
},
computed: {
showForm() {
return this.visibleForm;
},
getListId() {
return this.listId;
},
},
}
</script>

Related

When reload the page all data disappears in the page in ReactJS

Uncaught TypeError: Cannot read properties of null (reading 'imageLink')
The above error occurred in the <ProductMoreDetails> component:
This Products page Display all the products in the database. When I click on any product card it will redirects to the more details page of that product. First time it loads without any issue and when I refresh the page or backward the page it will disappear all the content in the page.
ProductMoreDetails.js
import Navbar from "../components/Navbar";
import { useProductsContext } from "../hooks/useProductsContext";
import { useParams } from "react-router-dom";
import { useEffect } from "react";
//setproducts
const ProductMoreDetails = () => {
const {products,dispatch} = useProductsContext();
const {id} = useParams();
useEffect(() => {
const fetchProducts = async () => {
const response = await fetch(`/api/products/${id}`)
const json = await response.json()
if (response.ok) {
dispatch({type: 'SET_PRODUCTS', payload: json})
}
}
fetchProducts()
},[dispatch,id])
return (
<div className="moredetails">
<Navbar/>
<br /><br />
<div className="details">
<img className="productImage" src={products.imageLink} alt="productImage" />
<div className="details-section"></div>
<div className="row section1">
<div className="col-lg-8">
</div>
<div className="col-lg-2">
<button className="btn btn-primary addnew">Add to Cart</button>
</div>
</div>
<div className="row section1">
<div className="col-lg-8">
<h1>{products.productName}</h1>
</div>
<div className="col-lg-2">
<h1>Rs. {products.price}</h1>
</div>
</div>
<div className="section1">
<hr />
<h1>Product Details</h1>
<br />
<div className="row">
<div className="col-lg-6">
<div className="row">
<div className="col-lg-6">
<h6>Category</h6>
</div>
<div className="col-lg-6">
<p>{products.category}</p>
</div>
</div>
</div>
<div className="col-lg-6">
<div className="row">
<div className="col-lg-6">
<h6>Brand</h6>
</div>
<div className="col-lg-6">
<p>{products.brand}</p>
</div>
</div>
</div>
</div>
<br />
<div className="row">
<div className="col-lg-6">
<div className="row">
<div className="col-lg-6">
<h6>Model</h6>
</div>
<div className="col-lg-6">
<p>{products.model}</p>
</div>
</div>
</div>
<div className="col-lg-6">
<div className="row">
<div className="col-lg-6">
<h6>Year</h6>
</div>
<div className="col-lg-6">
<p>{products.year}</p>
</div>
</div>
</div>
</div>
<br />
<div className="row">
<div className="col-lg-6">
<div className="row">
<div className="col-lg-6">
<h6>Features</h6>
</div>
<div className="col-lg-6">
<p>{products.features}</p>
</div>
</div>
</div>
</div>
<hr />
<div className="section2">
<h1>Product Description</h1>
</div>
<p>
{products.description}
</p>
</div>
</div>
</div>
)
}
export default ProductMoreDetails;
ProductContext.js
import { createContext } from "react";
import { useReducer } from "react";
export const ProductsContext = createContext();
export const productsReducer = (state, action) => {
switch (action.type) {
// set products
case "SET_PRODUCTS":
return {
...state,
products: action.payload,
}
//set a single product
case "SET_PRODUCT":
return {
...state,
products: action.payload,
}
case 'CREATE_PRODUCT':
return {
products: [action.payload, ...state.products]
}
case 'DELETE_PRODUCT':
return {
products: state.products.filter((product) => product._id !== action.payload._id)
}
case 'UPDATE_PRODUCT':
return {
products: state.products.map((product) => product._id === action.payload._id ? action.payload : product)
}
default:
return state;
}
}
export const ProductsContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(productsReducer, {
products: null
})
return (
<ProductsContext.Provider value={{...state, dispatch}}>
{ children }
</ProductsContext.Provider>
)
}

Vue not opens .json file with axios hook

Making my first steps in vue. I am crashing in importing a .json file. This job concernes a small shop. Goal of this paragraph is to enter 4 products in the shop. The productfiles are imported with an Axios hook. But the Vue Dev Tool errors an undefined (see picture). When loading the website the div with v-else is automatically loaded.
The products.json files is nested in the same folder as index.html. http://localhost:8000/products.json shows me the .json file.
Here you 'll find all the code for this small shop. Even with a copy/paste of this code mine is not working. I also made it smaller with the relevant code:
<!DOCTYPE html>
<html>
<head>
<title>Vue.js Pet Depot</title>
<script src="https://unpkg.com/vue"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/app.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.js"></script>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<div id="app">
<header>
<div class="navbar navbar-default">
<div class="navbar-header">
<h1>{{ sitename }}</h1>
</div>
<div class="nav navbar-nav navbar-right cart">
<button type="button" class="btn btn-default btn-lg" v-on:click="showCheckout">
<span class="glyphicon glyphicon-shopping-cart">{{ cartItemCount}}</span> Checkout
</button>
</div>
</div>
</header>
<main>
<div v-if="showProduct"> <!--not working-->
<div v-for="product in sortedProducts">
<div class="row">
<div class="col-md-5 col-md-offset-0">
<figure>
<img class="product" v-bind:src="product.image">
</figure>
</div>
<div class="col-md-6 col-md-offset-0 description">
<h1 v-text="product.title"></h1>
<p v-html="product.description"></p>
<p class="price">
{{product.price | formatPrice}}
</p>
<button class=" btn btn-primary btn-lg" v-on:click="addToCart(product)" v-if="canAddToCart(product)">Add to cart</button>
<button disabled="true" class=" btn btn-primary btn-lg" v-else>Add to cart</button>
<span class="inventory-message" v-if="product.availableInventory - cartCount(product.id) === 0">
All Out!
</span>
<span class="inventory-message" v-else-if="product.availableInventory - cartCount(product.id) < 5">
Only {{product.availableInventory - cartCount(product.id)}} left!
</span>
<span class="inventory-message" v-else>
Buy Now!
</span>
<div class="rating">
<span v-bind:class="{'rating-active' :checkRating(n, product)}" v-for="n in 5">
☆
</span>
</div>
</div>
<!-- end of col-md-6-->
</div>
<!-- end of row-->
<hr />
</div>
<!-- end of v-for-->
</div>
<!-- end of showProduct-->
<div v-else>
<!--skipped this part-->
</div>
</main>
</div>
<!-- end of app-->
</div>
<script type="text/javascript">
var APP_LOG_LIFECYCLE_EVENTS = true;
var webstore = new Vue({
el: '#app',
data: {
sitename: "Vue.js Pet Depot",
showProduct: true,
a: false,
states: []
},
order: []
},
products: [],
cart: []
},
methods: {
checkRating(n, myProduct) {
return myProduct.rating - n >= 0;
},
addToCart(aProduct) {
this.cart.push(aProduct.id);
},
showCheckout() {
this.showProduct = this.showProduct ? false : true;
},
submitForm() {
alert('Submitted');
},
canAddToCart(aProduct) {
//return this.product.availableInventory > this.cartItemCount;
return aProduct.availableInventory > this.cartCount(aProduct.id);
},
cartCount(id) {
let count = 0;
for (var i = 0; i < this.cart.length; i++) {
if (this.cart[i] === id) {
count++;
}
}
return count;
}
},
computed: {
cartItemCount() {
return this.cart.length || '';
},
sortedProducts() {
if (this.products.length > 0) {
let productsArray = this.products.slice(0);
console.log(productsArray);
console.log(this.products);
function compare(a, b) {
if (a.title.toLowerCase() < b.title.toLowerCase())
return -1;
if (a.title.toLowerCase() > b.title.toLowerCase())
return 1;
return 0;
}
return productsArray.sort(compare);
}
}
},
filters: {
formatPrice(price) { //#B
..
}
},
beforeCreate: function () { //#B
if (APP_LOG_LIFECYCLE_EVENTS) { //#B
..
},
created: function () {
axios.get('./products.json')
.then((response) => {
this.products = response.data.products;
console.log(this.products);
});
},
beforeMount: function () {
..
},
mounted: function () {
..
},
beforeUpdate: function () {
..
},
updated: function () {
..
},
beforeDestroyed: function () {
..
},
destroyed: function () {
..
}
});
</script>
</body>
</html>
I tried out the same code here and it's working fine, i had did axios call to this json file :
https://raw.githubusercontent.com/ErikCH/VuejsInActionCode/master/chapter-05/products.json
<!DOCTYPE html>
<html>
<head>
<title>Vue.js Pet Depot</title>
<script src="https://unpkg.com/vue"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/app.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.js"></script>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<div id="app">
<header>
<div class="navbar navbar-default">
<div class="navbar-header">
<h1>{{ sitename }}</h1>
</div>
<div class="nav navbar-nav navbar-right cart">
<button type="button" class="btn btn-default btn-lg" v-on:click="showCheckout">
<span class="glyphicon glyphicon-shopping-cart">{{ cartItemCount}}</span> Checkout
</button>
</div>
</div>
</header>
<main>
<div v-if="showProduct">
<div v-for="product in sortedProducts">
<div class="row">
<div class="col-md-5 col-md-offset-0">
<figure>
<img class="product" v-bind:src="product.image">
</figure>
</div>
<div class="col-md-6 col-md-offset-0 description">
<h1 v-text="product.title"></h1>
<p v-html="product.description"></p>
<p class="price">
{{product.price | formatPrice}}
</p>
<button class=" btn btn-primary btn-lg" v-on:click="addToCart(product)" v-if="canAddToCart(product)">Add to cart</button>
<button disabled="true" class=" btn btn-primary btn-lg" v-else>Add to cart</button>
<span class="inventory-message" v-if="product.availableInventory - cartCount(product.id) === 0">All Out!
</span>
<span class="inventory-message" v-else-if="product.availableInventory - cartCount(product.id) < 5">
Only {{product.availableInventory - cartCount(product.id)}} left!
</span>
<span class="inventory-message" v-else>Buy Now!
</span>
<div class="rating">
<span v-bind:class="{'rating-active' :checkRating(n, product)}" v-for="n in 5">☆
</span>
</div>
</div>
<!-- end of col-md-6-->
</div>
<!-- end of row-->
<hr />
</div>
<!-- end of v-for-->
</div>
<!-- end of showProduct-->
<div v-else>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-info">
<div class="panel-heading">Pet Depot Checkout</div>
<div class="panel-body">
<div class="form-group">
<div class="col-md-12">
<h4>
<strong>Enter Your Information</strong>
</h4>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<strong>First Name:</strong>
<input v-model.trim="order.firstName" class="form-control" />
</div>
<div class="col-md-6">
<strong>Last Name:</strong>
<input v-model.trim="order.lastName" class="form-control" />
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<strong>Address:</strong>
</div>
<div class="col-md-12">
<input v-model.trim="order.address" class="form-control" />
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<strong>City:</strong>
</div>
<div class="col-md-12">
<input v-model.trim="order.city" class="form-control" />
</div>
</div>
<div class="form-group">
<div class="col-md-2">
<strong>State:</strong>
<select v-model="order.state" class="form-control">
<option disabled value="">State</option>
<option v-for="(state, key) in states" v-bind:value="state">
{{key}}
</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<strong>Zip / Postal Code:</strong>
<input v-model.number="order.zip" class="form-control" type="number" />
</div>
</div>
<div class="form-group">
<div class="col-md-6 boxes">
<input type="checkbox" id="gift" value="true" v-bind:true-value="order.sendGift" v-bind:false-value="order.dontSendGift" v-model="order.gift">
<label for="gift">Ship As Gift?</label>
</div>
</div>
<!-- end of form-group -->
<div class="form-group">
<div class="col-md-6 boxes">
<input type="radio" id="home" v-bind:value="order.home" v-model="order.method">
<label for="home">Home</label>
<input type="radio" id="business" v-bind:value="order.business" v-model="order.method">
<label for="business">Business</label>
</div>
</div>
<!-- end of form-group-->
<div class="form-group">
<div class="col-md-6">
<button type="submit" class="btn btn-primary submit" v-on:click="submitForm">Place Order</button>
</div>
<!-- end of col-md-6-->
</div>
<!-- end of form-group-->
<div class="col-md-12 verify">
<pre>
First Name: {{order.firstName}}
Last Name: {{order.lastName}}
Address: {{order.address}}
City: {{order.city}}
Zip: {{order.zip}}
State: {{order.state}}
Method: {{order.method}}
Gift: {{order.gift}}
</pre>
</div>
<!-- end of col-md-12 verify-->
</div>
<!--end of panel-body-->
</div>
<!--end of panel panel-info-->
</div>
<!--end of col-md-10 col-md-offset-1-->
</div>
<!--end of row-->
</div>
</main>
</div>
<!-- end of app-->
</div>
<script type="text/javascript">
var APP_LOG_LIFECYCLE_EVENTS = true;
var webstore = new Vue({
el: '#app',
data: {
sitename: "Vue.js Pet Depot",
showProduct: true,
a: false,
states: {
AL: 'Alabama',
AK: 'Alaska',
AR: 'Arizona',
CA: 'California',
NV: 'Nevada'
},
order: {
firstName: '',
lastName: '',
address: '',
city: '',
zip: '',
state: '',
method: 'Home Address',
business: 'Business Address',
home: 'Home Address',
gift: '',
sendGift: 'Send As A Gift',
dontSendGift: 'Do Not Send As A Gift'
},
products: {},
cart: []
},
methods: {
checkRating(n, myProduct) {
return myProduct.rating - n >= 0;
},
addToCart(aProduct) {
this.cart.push(aProduct.id);
},
showCheckout() {
this.showProduct = this.showProduct ? false : true;
},
submitForm() {
alert('Submitted');
},
canAddToCart(aProduct) {
//return this.product.availableInventory > this.cartItemCount;
return aProduct.availableInventory > this.cartCount(aProduct.id);
},
cartCount(id) {
let count = 0;
for (var i = 0; i < this.cart.length; i++) {
if (this.cart[i] === id) {
count++;
}
}
return count;
}
},
computed: {
cartItemCount() {
return this.cart.length || '';
},
sortedProducts() {
if (this.products.length > 0) {
let productsArray = this.products.slice(0);
function compare(a, b) {
if (a.title.toLowerCase() < b.title.toLowerCase())
return -1;
if (a.title.toLowerCase() > b.title.toLowerCase())
return 1;
return 0;
}
return productsArray.sort(compare);
}
}
},
filters: {
formatPrice(price) { //#B
if (!parseInt(price)) {
return "";
} //#C
if (price > 99999) { //#D
var priceString = (price / 100).toFixed(2); //#E
var priceArray = priceString.split("").reverse(); //#F
var index = 3; //#F
while (priceArray.length > index + 3) { //#F
priceArray.splice(index + 3, 0, ","); //#F
index += 4; //#F
} //#F
return "$" + priceArray.reverse().join(""); //#G
} else {
return "$" + (price / 100).toFixed(2); //#H
}
}
},
created: function() { //#C
axios.get('https://raw.githubusercontent.com/ErikCH/VuejsInActionCode/master/chapter-05/products.json')
.then((response) => {
this.products = response.data.products;
// console.log(this.products);
});
}
});
</script>
</body>
</html>

User not defined issue for specific controller while passing data to view page in express nodejs

I am using express js as framework and ejs for view engine now for specific controller while passing data from controller to view it shows user not define with in view/partial/header.ejs which is working fine for other controller.
Controller code:
app.get('/add_home_content', function(req, res) {
User.findById(req.user, function(err, doc) {
if (doc.local.role == 'admin') {
var catId = '59f9be1aa40c152bc990f98f';
var contentid2 = '59faef18ce5da81b59c70a34';
var homeimgid = "59fc0e3e20942a15d7633cfd";
var contentplanid = "5a002bf79a62fc0bf2f14bbe";
content.findById(catId, function(err, content) {
//content.find({} ,{ "type": "homepage" }, function (err, content) {
//res.send(req.user.local);
trainercontent.findById(contentid2, function(err, trainercontent) {
homeimage.findById(homeimgid, function(err, homeimage) {
trainerinfo.find({}).exec(function(err, trainerinf) {
traininginfo.find({}).exec(function(err, traininginf) {
subscplancontent.findById(contentplanid, function(err, plancontent) {
banner.find({}).exec(function(err, bannerinf) {
// notification.find({}).exec(function(err, notifications) {
//res.send(content);
//trainercontent.find({}).exec(function(err, trainercontent) {
// res.send(notifications);
res.render('admin/content/addcontent.ejs', {
editContent: content,
editcontent2: trainercontent,
editcontent3: homeimage,
trainerinfo: trainerinf,
traininginfo: traininginf,
plancontents: plancontent,
bannerinfo: bannerinf,
message: false,
user: req.user.local
});
});
});
});
});
});
});
});
}
});
});
View page code(view engine ejs code) Showing user undefined error:
<script type="text/javascript">
/********signUp form validation *********/
$(document).ready(function() {
$('#planAdd').submit(function(e) {
var valid = $("#planAdd").valid();
if (valid) {} else {
e.preventDefault();
}
});
$('#planAdd').validate({
rules: {
'plan_name': 'required',
'price': 'required',
'currency': 'required',
'plan_duration': 'required'
},
messages: {
plan_name: {
required: "Plan can't be blank"
},
price: {
required: "Price can't be blank"
},
currency: {
required: "Currency can't be blank",
},
plan_duration: {
required: "Plan Duration can't be blank"
}
}
});
});
/********end of form validation *********/
</script>
<div class="page-inner">
<% if (message.length > 0) { %>
<div class="alert alert-danger">
<%= message %>
</div>
<% } %>
<div id="main-wrapper">
<a class="btn btn-success btn-lg " href="javascript: history.go(-1)">←Back To previous page</a>
<div class="row">
<div class="col-sm-2"></div>
<div class="col-sm-8 add-plan-form">
<div class="row m-t-md">
<h1 class="add-plan-heading">Add Content</h1>
<script type="text/javascript">
$(document).ready(function(){
$("#myTab li:eq(0) a").tab('show');
});
</script>
<style type="text/css">
.bs-example{
margin: 20px;
}
.col-sm-8 {
width: 96.667%;
}
#media (min-width: 320px) and (max-width: 480px){
#myTab li {
width: 100%;
margin: 5px 0;
}
}
#media (min-width: 481px) and (max-width: 640px){
#myTab li {
width: 50%;
margin: 5px 0;
padding: 5px;
}
}
#media (min-width: 641px) and (max-width: 767px){
#myTab li {
width: 33%;
margin: 5px 0;
padding: 5px;
}
}
</style>
</head>
<body>
<div class="bs-example">
<ul class="nav nav-tabs" id="myTab">
<li><a data-toggle="tab" href="#sectionA">Home page content</a></li>
<li><a data-toggle="tab" href="#sectionB">Trainer content</a></li>
<li><a data-toggle="tab" href="#sectionc">Home page bottom content</a></li>
<li><a data-toggle="tab" href="#sectiond">Trainers</a></li>
<li><a data-toggle="tab" href="#sectione">Add training type</a></li>
<li><a data-toggle="tab" href="#sectionf">Subscription plan content</a></li>
<li><a data-toggle="tab" href="#sectiong">Add Banner</a></li>
</ul>
<div class="tab-content clearfix">
<div id="sectionA" class="tab-pane fade in active">
<form action="/updateContent?id=<%= editContent.id %>" method="POST" id="planAdd">
<div class="form-group">
<label>Content Heading</label>
<input type="text" class="form-control" name="content_heading" value="<%= editContent.content_heading %>">
</div>
<div class="form-group">
<label>Content Description</label>
<textarea rows="7" cols="50" name="content_desc" class="form-control" ><%= editContent.content_desc %>
</textarea>
<span class="Phon_err"></span>
</div>
<button type="submit" class="btn btn-warning btn-lg">Save</button>
</form>
</div>
<div id="sectionB" class="tab-pane fade">
<form action="/updatetrainContent?id=<%= editcontent2.id %>" method="POST" id="categoryAdd">
<div class="form-group">
<label>Heading</label>
<input type="text" class="form-control" name="heading" value="<%= editcontent2.heading %>">
</div>
<div class="form-group">
<label>Description</label>
<!-- <input type="text" class="form-control" name="desc"> -->
<textarea rows="7" cols="50" name="desc" class="form-control" ><%= editcontent2.desc %>
</textarea>
</div>
<button type="submit" class="btn btn-warning btn-lg">Save</button>
</form>
</div>
<div id="sectionc" class="tab-pane fade">
<form action="/add_img?id=<%= editcontent3.id %>" method="post" id="videoAdd" enctype="multipart/form-data" >
<div class="form-group">
<label>Heading</label>
<input type="text" class="form-control" name="title" value="<%= editcontent3.title %>" >
</div>
<div class="form-group img-d">
<label > Thumbnail</label>
<div "><input type="file" class="" id="e_Img_file" name=" home_img"></div>
<img src="./uploads/homepageimage/<%= editcontent3.home_img %>" height="200" width="220">
<span class="value"></span>
</div>
<button type="submit" class="btn btn-success btn-lg pull-right">Save</button>
</form>
</div>
<div id="sectiond" class="tab-pane fade in active m-div clearfix">
<h2 class="h-div">
Add new trainer</h2>
<!-- <% if(trainerinfo){ trainerinfo.forEach( function (trainerinf){ %>
<div class="members animated fadeInLeft visible" data-animation="fadeInLeft" data-animation-delay="300"><div class="content_slider_text_block_wrap"><div class="team-img"><img src="/uploads/trainerprofile/<%- trainerinf.trainer_profile %>" alt="image" class="member_photo" width="250" height="320"></div><div class="team-inner"><div class="team-top center"><h4 class="membername"><%- trainerinf.trainer_name %></h4><br><span class="membername_dec"><%- trainerinf.trainig_type %></span></div></div></div><div class="clear"></div></div><div class="sharemedeia"><a target="_self" href="<%- trainerinf.trainer_facebook %>"><i class="fa fa-facebook"></i></a><a target="_self" href="<%- trainerinf.trainer_twiter %>"><i class="fa fa-twitter"></i></a><a target="_self" href="<%- trainerinf.trainer_google %>"><i class="fa fa-google-plus"></i></a></div>
Edit
Delete
<% }); }%> -->
<div class="members_section">
<div class="row">
<% if(trainerinfo){ trainerinfo.forEach( function (trainerinf){ %>
<div class="col-sm-4 col-xs-6 team_m">
<img src="/uploads/trainerprofile/<%- trainerinf.trainer_profile %>" alt="image" class="member_photo img-responsive">
<h4 class="membername"><%- trainerinf.trainer_name %><span class="membername_dec">(<%- trainerinf.trainig_type %>)</span></h4>
<div class="sharemedeia">
<a target="_self" href="%- trainerinf.trainer_facebook"><span class="s-bg"><i class="fa fa-facebook"></i></span></a>
<a target="_self" href=""<%- trainerinf.trainer_twiter %>"><span class="s-bg"><i class="fa fa-twitter"></i></span></a>
<a target="_self" href="<%- trainerinf.trainer_google %>"><span class="s-bg"><i class="fa fa-google-plus"></i></span></a></div>
<div class="ed_de">
Edit
Delete
</div>
</div> <!--col-sm-4-->
<% }); }%>
</div> <!--row-->
</div> <!--members_section-->
</div>
<div id="sectione" class="tab-pane fade in active">
<h2 class="h-div"><a href="/addtrainingtype" >Add new training type</a></h2>
<div class="members_section">
<div class="row">
<% if(traininginfo){ traininginfo.forEach( function (traininginf){ %>
<div class="col-sm-4 col-xs-6 team_m">
<img src="/uploads/trainingtype/<%- traininginf.training_profile %>" alt="image" class="member_photo img-responsive">
<h4 class="membername"><%- traininginf.trainer_title %></h4>
<div class="ed_de">
Edit
Delete
</div>
</div> <!--col-sm-4-->
<% }); }%>
</div> <!--row-->
</div> <!--members_section-->
</div>
<div id="sectionf" class="tab-pane fade in active">
<form action="/subsplanContent?id=<%= plancontents.id %>" method="POST" id="planAdd">
<div class="form-group">
<label>Heading</label>
<input type="text" class="form-control" name="title" value="<%= plancontents.title %>" >
</div>
<div class="form-group">
<label>Content Description</label>
<textarea rows="7" cols="50" name="content_desc" class="form-control" ><%= plancontents.content_desc %>
</textarea>
<span class="Phon_err"></span>
</div>
<button type="submit" class="btn btn-warning btn-lg">Save</button>
</form>
</div>
<div id="sectiong" class="tab-pane fade in active">
<h2 class="h-div">
Add banner image</h2>
<div class="members_section">
<div class="row">
<% if(bannerinfo){ bannerinfo.forEach( function (bannerinf){ %>
<div class="col-sm-4 col-xs-6 team_m">
<img src="/uploads/bannerimage/<%- bannerinf.banner_image %>" alt="image" class="member_photo img-responsive">
<div class="ed_de">
Edit
Delete
</div>
</div> <!--col-sm-4-->
<% }); }%>
</div> <!--row-->
</div> <!--members_section-->
</div>
</div>
</div>
</body>
</html>
</div>
</div>
</div>
</div>

SailsJS : Mysterious null values

my problem is that whenever a new client is created, all the values are null in the database except the id, the name, responsable and the logo. i dont think i did a programmation mistake, so i think it is a case of callbacks race but i cant found the solution.
P.S : the problem occure only if i select and send an image file to be uploaded, in the other case, the client values are stored correctly.
P.S 2 : the problem occure in my remote server only, in local environnement all is ok !
Than you very much !
UPDATE : i included the code for my create.ejs view
This is the code of the store method in my ClientService :
store: function(req, done) {
var name = req.param('name'),
town = req.param('town'),
adress = req.param('adress'),
postalCode = req.param('postalCode'),
telephone = req.param('telephone'),
email = req.param('email'),
fax = req.param('fax'),
responsable = req.param('responsable'),
website = req.param('website'),
activity = req.param('activity');
comments = req.param('comments');
Client.create({
name: name,
town: town,
adress: adress,
postalCode: postalCode,
telephone: telephone,
fax: fax,
responsable: responsable,
website: website,
activity: activity,
email: email,
comments: comments
}).exec(function(err, client) {
if (err) console.log(err);
req.file('logo').upload(
{
dirname: sails.config.appPath + sails.config.params.logos
},
function(err, logo) {
if (err) return done(err, null);
if (logo.length !== 0) {
client.logo = require('path').basename(logo[0].fd);
} else {
client.logo = 'default.png';
}
client.save(function(err) {
return done(null, client);
});
}
);
});
}
And this is the code for the EJS view :
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="store" method="POST" class="form-horizontal" enctype="multipart/form-data">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="name">
<label for="form_control_1">Nom du Client</label>
<i class="fa fa-institution"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="activity">
<label for="form_control_1">Activité</label>
<i class="icon-star"></i>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="responsable">
<label for="form_control_1">Responsable</label>
<i class="icon-user"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group" style="margin-left:15px;">
<div class="form-photo-label-form" >
<i class="icon-picture icon-create"></i>
<label for="form_control_1" class="form-photo-create" >Photo </label>
</div>
<br>
<div class="fileinput fileinput-new" data-provides="fileinput">
<span class="btn green btn-file">
<span class="fileinput-new"> Selectionner Fichier </span>
<span class="fileinput-exists"> Changer </span>
<input type="file" name="logo"> </span>
<span class="fileinput-filename"> </span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="email">
<label for="form_control_1">Email</label>
<i class="fa fa-inbox"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="adress">
<label for="form_control_1">Adresse</label>
<i class="icon-home"></i>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="postalCode">
<label for="form_control_1">Code postale</label>
<i class="fa fa-send"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="town">
<label for="form_control_1">Ville</label>
<i class=" fa fa-map"></i>
</div>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-12">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<textarea class="form-control" rows="3" style="height: 192px; resize:none " name="comments"></textarea>
<label for="form_control_1">Commentaire</label>
<i class=" fa fa-edit"></i>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-12">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="telephone">
<label for="form_control_1">Telephone</label>
<i class="icon-screen-smartphone"></i>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="fax">
<label for="form_control_1">Fax</label>
<i class="fa fa-fax"></i>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="website">
<label for="form_control_1">Site Internet</label>
<i class=" fa fa-internet-explorer"></i>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-actions right">
<button type="button" class="btn default">Annuler</button>
<button type="submit" class="btn green"><i class="fa fa-check"></i> Enregistrer</button>
</div>
</form>
Nothing mysterious (:
Your problem is that You use req.param instead of req.body
And Your code is simply should look like this:
const path = require('path'); // somewhere in same module at the top
store: (req, done) => {
Client
.create(req.body)
.exec((err, client) => {
if(err) {
// no need to go further
// if You cannot create database record
return done(err);
}
const dirname = path.join(sails.config.appPath, sails.config.params.logos); // safely concatenates paths based on OS
req
.file('logo')
.upload({dirname}, (err, logo) => {
if (err) {
// we created record (client)
// but could not save the file
// it should not be a stopper
console.error(err);
}
client.logo = (logo) ? path.basename(logo[0].fd) : 'default.png';
client.save((err) => {
if(err) {
// just log the error and continue
console.error(err);
}
done(null, client);
});
});
});
}
P.S. When You pass req.body (or any other) object to Client.create don't worry about object contents, just define field constrains in You model file, ODM (or ORM) will just handle validation automatically based on constraints and will prevent from creating null valued fields
Example:
module.exports = {
attributes: {
name: {
// it requires field name:
// to be defined (required: true),
// to be string (type),
// to have at least 2 symbols,
// to not exceed 100 symbols
type: 'string',
required: true,
minLength: 2,
maxLength: 100
},
email: {
// it requires field email:
// to be defined (required: true),
// to be email (type),
// to be unique among documents, records, rows
type: 'email',
required: true,
unique: true
},
... and so on ...
}
}
More about validation here
Thanks everybody. I solved the problem by putting the file input at the end the form. Like you suggested, the values after the file input were reset after the upload of the file

Vue.js - Working with Components

I am new to Vue.js. Very new so this question might sound a lot like a first graders. Forgive me.
I have the App.vue and Character.vue setup. I wanted to create characters on the fly and add them to an array (in App.vue) and let the rendering of the look/feel of the characters be done using Character.vue. The characters are created and added to the array and can be retrieved properly. Only thing is...Character.vue doesn't render them properly because for some reason, the character it retrieves from the array is undefined.
Help me?
Attaching files
App.vue
<template>
<div>
<div class='gameHeader'>
<h1>{{ gameHeader }}</h1>
</div>
<div class='gameMessages'>
<div class='gameMessage' v-for="msg in gameMessages">
{{ msg }}
</div>
</div>
<div class='gameMain'>
<button #click="rollNewCharacter">Roll New</button>
<div class="playerParty">
<character v-for="p in playerParty"></character>
</div>
<div class="computerParty">
<character v-for="c in computerParty"></character>
</div>
</div>
<div class='gameFooter'>
{{ gameFooter }}
</div>
</div>
</template>
<script>
import Character from "./assets/components/Character.vue";
export default {
components: { 'character': Character },
data: function(){ return { gameHeader: 'Monster Attack', gameMessages:[], playerParty: [], computerParty: [], gameFooter: '' }; },
methods: {
rollNewCharacter() {
var c = Character;
c.name = 'Usman';
c.type = 'Warrior';
c.mana = 100;
c.health = 100;
c.totalHealth = 100;
c.totalMana = 100;
console.log(c.name);
this.playerParty.push(c);
console.log(this.playerParty[0].name);
//this.computerParty.push(chr2);
}
}
}
</script>
Character.vue
<template>
<div class="character">
<span class='name'>{{ name }}</span><span class='type'>({{ type }})</span>
<div class='health'><div class='total' :class="totalHealth"><div class='health' :class="health"></div></div></div>
<div class='mana'><div class='total' :class="totalMana"><div class='mana' :class="mana"></div></div></div>
<span class='damage'>{{ damage }}</span>
<div class="actions">
<button #click="attack">Attack</button>
<button #click="specialAttack">Special Attack</button>
<button #click="heal">Heal</button>
</div>
</div>
</template>
<script>
export default {
props: [ 'name', 'type', 'mana', 'health', 'damage' , 'totalHealth', 'totalMana' ],
methods: {
attack: function(){},
specialAttack: function(){},
heal: function(){ alert(this.name); console.log(this);}
}
}
</script>
<style>
</style>
You should pass a prop when using the character component:
<character :character="p" v-for="p in playerParty"></character>
I have updated the character to receive only one prop:
export default {
props: [ 'character' ],
methods: {
attack: function(){},
specialAttack: function(){},
heal: function(){ alert(this.name); console.log(this);}
}
}
And this is the character component template with the new prop:
<template>
<div class="character">
<span class='name'>{{ character.name }}</span><span class='type'>({{ character.type }})</span>
<div class='health'><div class='total' :class="character.totalHealth"><div class='health' :class="character.health"></div></div></div>
<div class='mana'><div class='total' :class="character.totalMana"><div class='mana' :class="character.mana"></div></div></div>
<span class='damage'>{{ character.damage }}</span>
<div class="actions">
<button #click="attack">Attack</button>
<button #click="specialAttack">Special Attack</button>
<button #click="heal">Heal</button>
</div>
</div>
</template>

Resources