how to use express.router to access data in url? (vue) - javascript

I have a file "app.vue" that implements a date picker for user to choose date:
//app.vue
<div id="q-app">
<div class="q-pa-md" style="max-width: 300px">
<q-input filled v-model="date" mask="date" :rules="['date']">
<template v-slot:append>
<q-icon name="event" class="cursor-pointer">
<q-popup-proxy>
<q-date v-model="date" ></q-date>
</q-popup-proxy>
</q-icon>
</template>
</q-input>
</div>
</div>
import { ref } from 'vue'
export default {
setup () {
return {
date: ref('2019/02/01')
}
}
methods: {
updateDate(){
this.$router.push({
name: this.$router.name,
query: this.date,
}
</script>
I tested "app.vue" successfully updates user selected date to the url.
I have another file "data.js" which is the backend, I want to get the user picked date, to do so, I try to access it like the following:
//data.js
const router = express.Router();
router.get("/", async function (req, res) {
...
console.log("user input date", req.query);
}
But the req.query is always returning empty.
Does anyone know why this is happening and how I can access the date data from "data.js"?

Related

Dynamically display fetched data in input field using Laravel 8 Vue Js

I have a simple registration form in Laravel 8 using Vue js where I need to check first if the user who refers the person registering exists in my database prior to submitting. if a record exists, I need to dynamically display the user's full name in the input field on the #change event.
Here's my Vue component:
<template>
<div>
<h2>TESTING</h2>
<form #submit.prevent="submit" >
<input type="text" class="form-control" v-model="form.ucode" #change="getUser()">
<input type="text" class="form-control" v-model="form.uname">
</form>
</div>
</template>
<script>
export default {
data: function(){
return{
form: {
ucode: "",
uname: "",
},
}
},
methods:{
getUser(){
axios.get('api/checkUser?ucode=' + this.form.ucode).then(res=>{
this.form.uname = res.data.first_name
})
}
}
}
Here's my ResellerController and API route:
Route::get('/checkUser', [ResellerController::class, 'show']);
public function show()
{
$ucode = request('ucode');
$user = DB::table('resellers')->where('username', $ucode)->select('id', 'first_name')->get();
return response()->json($user);
}
I think I don't have issues with my controller because it returns back the correct JSON data
[{"id":1,"first_name":"William Hardiev"}]
But when I test my code, uname is undefined.
form:Object
ucode:"williambola_05"
uname:undefined
Can anyone help me with this?
You issue is the JSON response that you receive from the server. You are getting a JSON Array from the server, whereas your JS code is handling a JSON object
You can handle it like this:
<template>
<div>
<h2>TESTING</h2>
<form #submit.prevent="submit">
<input
type="text"
class="form-control"
v-model="form.ucode"
#change="getUser()"
/>
<input type="text" class="form-control" v-model="form.uname" />
</form>
</div>
</template>
<script>
import axios from "axios";
export default {
data: function() {
return {
form: {
ucode: "",
uname: ""
}
};
},
methods: {
getUser() {
axios.get("api/checkUser/?ucode=" + this.form.ucode).then(res => {
this.form.uname = res.data[0].first_name;
});
}
}
};
</script>
OR you can just change the get query on the server side to simply return a single JSON object rather than an array and your js code should automatically start working:
$user = DB::table('resellers')
->where('username', $ucode)
->select('id', 'first_name')
->first();

Vuejs nuxtjs Store update not getting reflected in the middleware

I am new to VueJs and I tried to create a small application using nuxtJS where I have a login page and a home page. I am using middleware authjs to check if the user is authenticated to view the home page.
The vuex store contains a flag isLoggedIn to store the user's logged-in state. The issue I'm facing here is:
When I update the store from the login page(using commit function) and redirect to the home page, the store update is not reflected in the middleware which is called before the home page and I'm going back to the login page.
/pages/login.vue
<template>
<div>
<default-header />
<login-form :onSubmit="onSubmit" />
</div>
</template>
export default {
methods: {
async onSubmit(){
//fetching some data, skipped here for simplicity
this.$store.commit('marklogin')
this.$router.push('home')
}
}
}
/store/index.js
export const state = () => ({
loggedin: false
})
export const mutations = {
marklogin(state) {
state.loggedin = true
}
}
/middleware/auth.js
export default function ({ store, redirect }) {
if (!store.state.loggedin) {
return redirect('/login');
}
}
This is /pages/home.vue
<template>
<div>
<default-header />
<videos :videos="videos.data"/>
</div>
</template>
<script>
export default {
data() {
return {
videos: []
};
},
async fetch() {
this.videos = await fetch(
'http://localhost:8080/videos'
).then(res => res.json());
},
middleware: 'auth'
}
</script>
/components/Login.vue
<template>
<div class="container-form">
<h2>User Login</h2>
<b-form>
<b-form-group
id="input-group-1"
label-for="input-1"
>
<b-form-input
id="input-1"
v-model="form.username"
type="text"
required
:state="usernameValidation"
aria-describedby="input-live-help input-live-feedback"
placeholder="Enter your user name"
></b-form-input>
<b-form-invalid-feedback id="input-live-feedback">
Enter at least 3 letters
</b-form-invalid-feedback>
</b-form-group>
<b-form-checkbox
id="checkbox-1"
v-model="status"
name="checkbox-1"
value="accepted"
class="remember-me-checkbox"
>
Remember me
</b-form-checkbox>
</b-form>
<button type="button" #click="() => onSubmit(form.username)" class="login-button" variant="success">Login</button>
</div>
</template>
In the authjs, the value of store.state.loggedin is coming as false. Can someone help me understand why this is happening?

vue.js post list not updating after form submission

In my vue app I have two components one which is a form that posts the form data to my api. And the other gets and displays these posts in a section on the page. My issue is that when I submit a new post the posts lists aren't updated. The data stays the same unless I refresh the page. How can I get my posts list to update when I submit the form?
My Code:
client/src/App.vue
<template>
<div id="app">
<MainHeader :modalVisability="modal" v-on:showModal="toggleModal" />
<div id="content_wrap">
<Summary />
</div>
<OppForm :modalVisability="modal" />
</div>
</template>
<script>
import MainHeader from './components/MainHeader.vue';
import OppForm from './components/oppForm.vue';
import Summary from './components/Summary.vue';
export default {
name: 'App',
components: {
MainHeader,
Summary,
OppForm
},
data () {
return {
modal: false
}
},
methods: {
toggleModal (modalBool) {
this.modal = modalBool;
}
}
}
</script>
client/src/components/oppForm.vue
<template>
<div id="opp_form_modal" >
<form #submit.prevent="SubmitOpp" v-if="modalVisability">
<input type="text" name="company_name" v-model="company_name">
<button type="submit">Submit</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'oppForm',
props: {
modalVisability: Boolean,
},
data () {
return {
company_name: ''
}
},
methods: {
SubmitOpp () {
axios.post('http://localhost:5000/', {
company_name: this.company_name,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
}
</script>
client/src/components/Summary.vue
<template>
<div id="summary_section">
<h2>Summary</h2>
<div id="summary_board">
<div class="column">
<div class="head">
<h3>Opportunities</h3>
</div>
<div class="body">
<div class="post"
v-for="(post, index) in posts"
:key="index"
>
<p class="company">{{ post.company_name }}</p>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return{
posts: []
};
},
created() {
axios.get('http://localhost:5000/')
.then(res => {
// console.log(res);
const data = res.data;
this.posts = data;
})
.catch(error => console.log(error));
}
}
</script>
The problem is that you're actually fetching your posts only on the app creation (i.e. inside the created() method).
You should wrap your axios call inside a function updatePosts() and then call it whenever you add a new post successfully, or you could create a custom event that is triggered whenever a new post is added.
created() is called only once (see vue lifecycle) so you fetch API before submitting form.
Try to add some console.log to understand what is called when.
You could use an global event bus and send form value as event data to summary. I could imagine also a solution where event is used to "tell" summary that form was submitted (just boolean, not data itself). In summary you then call API each time you receive event.
Or simple add an "update" button to summary to manually call API.
See Communication between sibling components in VueJs 2.0
or global vue instance for events for detailed examples.

How to get data from firebase when page loading using vuejs?

I have been trying to get current user data from firebase to display details in profile page.
Here i am trying get data from firestore, when page loading. My table structure : users => Current user UID => email, firstname, lastname, businessname, etc.
I have added functionality to get data from firebase when profile page loading but does not work. error showing in console product.data().firstname is not function.
And also i did not get any console output firebase data retrieved or not?
here is my code:
<template>
<section class="what-we-do">
<div class="container-2" style="padding-top: 150px;">
<div class="row">
<div class="col-md-12">
<div class="saving-process-crd">
<div class="saving-process-inner">
<avatar :fullname="currentUser.email" size="96" >
</avatar>
<h4>Siva NSN</h4>
<h6 style="color:grey;">{{currentUser.email}}</h6><br><br>
<div class="card-columns" >
<div class="card" style="border: none; text-align: justify;">
<div class="card-body">
<h5 class="card-title">First Name:</h5><br>
<h5 class="card-title">Last Name:</h5><br>
<h5 class="card-title">Email ID:</h5><br>
</div>
</div>
<div class="card" style="border: none;">
<div class="card-body" style="float: left; text-align: left;" >
<h5 class="card-title">{{product.data().firstname}}</h5><br>
<h5 class="card-title">Mobility</h5><br>
<h5 class="card-title">{{currentUser.email}}</h5><br>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
import Avatar from 'vue-avatar-component'
import database from '#/database'
import firebase from 'firebase/app'
export default {
name: 'Profile',
computed:{
currentUser (){
return this.$store.state.currentUser
}
},
components: {
Avatar
},
data () {
return {
profileData:{
email:null,
firstname:null,
lastname:null,
secondaryEmail:null,
businessName:null
}
}
},
methods:{
readData(){
const firestore = database.firestore();
firestore.collection('users').doc(firebase.auth().currentUser.uid).
onSnapshot(function(doc){
console.log('current data:', doc.data())
var newData = doc.data()
this.profileData.push(newData)
})
}
}
}
</script>
main.js code:
here i am i have user authstatechanges of current user.
import Vue from 'vue'
import App from './App.vue'
import router from './router';
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './assets/styles//base-style.css';
import store from '#/store'
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
Vue.config.productionTip = false
let app
const initialize = () => {
if (!app) {
app = new Vue({
el: '#app',
router,
store,
render: h => h(App),
})
}
}
firebase.auth().onAuthStateChanged(user => {
if(user) {
store.commit('setCurrentUser', user)
} else {
store.commit('setCurrentUser', null)
}
initialize()
})
console output:
How to get data when page loading from firebase database. any help much appreicated pls..
There are number of things you have to adjust,
instead of fetching data using a method, try to add the code to a life cycle hook method, which will fire before you mount the data to dom, more precisely saying, use created lifecycle hook
https://vuejsexamples.net/vuejs-created/
Then you are populating the data to the template using currentUser which is taken from the vuex store,
return this.$store.state.currentUser, but in your firebase function you are setting the data you fetch to a data property which is profileData which is not used in the template.
You are pushing to profileData, but it's not an array it is a object and you cant push to an object.
So better flow is, fetch data using created lifecycle hook, then
either
store(mutate) the received data to the store.state.currentUser then it might work.
else update the profileData and replace the template with profileData instead of currentUser
Try this one,
Create a created lifecycle hook and move the firebase code to that. and assign the profileData object to the fetched Data.
created() {
const firestore = database.firestore();
firestore.collection('users').doc(firebase.auth().currentUser.uid).
onSnapshot(function(doc){
console.log('current data:', doc.data())
var newData = doc.data()
this.profileData = newData;
})
}
Then replace the currentUser in template to profileData.
ex : <h6 style="color:grey;">{{profileData.email}}</h6><br><br>

How to click on a user & show the user details in another component/view with Vuejs router?

I am doing a project with Vuejs and I need to the following:
Use an API & fetch a list of users (just the names of the users) in the home page.
Create a custom search filter to find users by name.
When clicking on a user's name, I need to redirect to another component & output that user's details in that component (only the details of the user that I clicked).
I have accomplished the first two tasks. However, I have no idea how doing the other third task. I was reading the documentation for vue-router, but I am not able to figure it out.
I used axios to fetch the list of users & jsonplaceholder.
User List Component:
<template>
<div>
<!-- List Rendering the response data stored in posts[] array -->
<b-input id="inline-form-input-name" class="my-3 col-10 col-sm-10 col-md-4 col-lg-4" type="text" v-model="searchUsers" placeholder="Search Users..."
></b-input>
<h2>Our users:</h2>
<div v-for="user in filteredUsers" :key="user.id">
<p v-b-tooltip.hover.right='"Click on user to know more"' class="users pr-2"><span>{{ user.id }}</span> - {{ user.name }}</p>
</div>
</div>
</template>
<script>
// import axios
import axios from 'axios'
export default {
name: 'UsersList',
data() {
return {
users: [],
searchUsers: ''
}
},
computed: {
// custom search box for user names
filteredUsers() {
return this.users.filter(user => {
return user.name.match(this.searchUsers)
})
}
},
// life cycle hook - calls axios
created(){
axios.get('https://jsonplaceholder.typicode.com/users').then(response => {
console.log(response.data)
this.users = response.data
// console.log an error if get() method is unsuccessful
}).catch(err => {
console.log(err)
})
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.users {
cursor: pointer;
display: inline-block;
}
</style>
The User list component's name is UserList.vue
I need to ouput the user detail in this component called UsersDetails.vue
<template>
<div class="user-details-wrapper">
<h1>I am the user details component</h1>
</div>
</template>
<script>
export default {
name: 'UserDetails',
data(){
return {
}
},
}
</script>
<style lang="scss">
.user-details-wrapper {
h1 {
background: #000;
color: #fff;
padding: 10px;
margin-top: 30px;
display: inline-block;
}
}
</style>
Screenshot user list & custom search filter
Any help will be truly appreciated it!
You can use Dynamic Route Matching
Add a route
const router = new VueRouter({
routes: [
// dynamic segments start with a colon
{ path: '/user/:id', component: User }
]
})
A dynamic segment is denoted by a colon : When a route is matched, the value of the dynamic segments will be exposed as this.$route.params in every component.
In the Single User component do an AJAX call in mounted
mounted() {
axios.get("https://jsonplaceholder.typicode.com/users/" + this.$route.params)
.then(res => console.log(res))
}

Categories