Watching for form data in nuxtjs - javascript

On my page I have a form,
<div v-if="this.userdata.address == ''">Please enter your address</div>
Your address
<input type="text" v-model="userdata.address">
Your phone
<input type="text" v-model="userdata.phone">
Your message
<input type="text" :disabled="this.userdata.address == '' ? true : false">
And my script section is:
<script>
export default {
data() {
return {
userdata: {
companydata: {}
}
}
}
}
.....
<script>
If my user is Authorized, "userdata" data will be filled in fetch().
My problem is to check, if address field filled in or not on the go, and then if user entered his address, make Message field active, but if he not filled it, or cleaned this field (if he authorized and data was loaded to form in fetch() method), make Message field disabled again.
Problem is that if I reload this page, everything is works, but if I navigate to it from other page, nothing is works.
Whats a problem can be?

I was missing the address data in my userdata. I managed to fix my problem simply by adding it as an empty string.
<script>
export default {
data() {
return {
userdata: {
address: "", //// Adding this solved my problem
companydata: {}
}
}
}
}
.....
<script>

Related

SvelteKit: cookies.set() In Form Action Not Working

I am trying to implement JWT-based user sessions with SvelteKit, and have mostly been following the explanation for form actions given on their website: https://kit.svelte.dev/docs/form-actions
+page.svelte
<form method="POST" action="?/signIn">
<input type="text" name="name" />
<input type="password" name="password" />
<button type="submit">Submit</button>
</form>
+page.server.svelte
import { fail, redirect } from "#sveltejs/kit";
import { signIn } from "$lib/server/database";
export const actions = {
signIn: async ({ cookies, request }) => {
const data = await request.formData();
const name = data.get("name");
const password = data.get("password");
if (!name || !password) {
return fail(400);
}
try {
cookies.set("jwt", await signIn(name, password));
} catch (error) {
return fail(400);
}
throw redirect(303, "/");
},
};
I have tested my signIn method which I import and use here, and it does return a token when called with the correct credentials. So far, so good. However, I noticed that I don't see any cookies in my developer tools. It seems like the cookies.set() call simply does nothing. I'd like to set the returned JWT as a cookie so that I can authenticate my users, so what am I doing wrong?
In case anybody else has this problem: While the cookie was set as it was supposed to when using Chrome, it wasn't in Safari. I solved this by setting the secure option to false, even though the SvelteKit docs state that this is done automatically on localhost.

SessionStorage Slow Loading

I'm using SessionStorage data to display the username on the screen. The name should load after login, but the information is only loaded when I refresh the page (clicking on reload).
Does anyone know why?
HTML
<cv-header-name to="/"> Welcome {{ userName }}</cv-header-name>
VUE
data: function () {
return {
userName: [],
};
},
mounted() {
if(sessionStorage.getItem('name')) {
try {
this.userName = JSON.parse(sessionStorage.getItem('name'))
}catch (error) {
sessionStorage.removeItem('name')
}
}
}
Before refresh
enter image description here
After refresh
enter image description here

Nuxt.js page reloading on for submission even with stop.prevent

I've been reading some questions about this exact same topic like but none of them seems to be working for me and I can't spot the error.
I have this form:
<template>
<div class="container">
<form #submit.stop.prevent="submit">
<input v-model="name" type="text" />
<input v-model="email" type="text" />
<button type="submit">Submit</button>
</form>
</div>
</template>
And the following script
<script>
export default {
data() {
return {
name: '',
email: ''
}
},
methods: {
async submit() {
const res = await this.$axios.request({
url: 'locahost:3000/404', // This route doesn't exists
method: 'post',
data: this.$data
})
console.log(res.status)
}
}
}
</script>
As you can see, there are more than one input in the form and I'm using stop.prevent when binding the submit event in the form.
I want to treat any possible errors in the axios request in the script part and update the page based on that (showing an error div or whatever) but without reloading it. However, the page reloads and is going to a 404 error page.
I'm using Nuxt 2.12.2 and I can't see what I'm doing wrong. Any help would be appreciated.
Thanks all!
You can omit the form behaviour by only using the data in your submit method and trigger it by #click on the button without any submit type, like this :
<template>
<div class="container">
<form>
<input v-model="name" type="text" />
<input v-model="email" type="text" />
<button #click="() => submit()">Submit</button>
</form>
</div>
</template>
Like this you will avoid any kind of side effect from the form as you don't need any form data in your axios request...
Ok, I found the answer just by trial and error and it was easier than I thought... It was only about unhandled promise rejection. As I'm using async/await I need to treat exceptions correctly and I was not doing that, the rejection was being propagated and the error handled by nuxt. So changing my code to:
<script>
export default {
data() {
return {
name: '',
email: ''
}
},
methods: {
async submit() {
try {
const res = await this.$axios.request({
url: 'locahost:3000/404', // This route doesn't exists
method: 'post',
data: this.$data
})
console.log(res.status)
} catch (err) {
console.log(err)
}
}
}
}
</script>
That will prevent the error to be handled elsewhere and resulting in a redirection to a 404 page or whatever.

How to prevent user from submitting text that already exists in a remote api?

I am creating a VueJS app that contains a list of names called divisions. The user can submit a new name for a division and can also update a division name. The names of the divisions are received from a remote api and any edits made are then also sent to the api via a PUT request. This works well.
However, the problem is how can I prevent a user from submitting a division name that already exists?
I have a parent component (named Divisions.vue) that contains a GET request like so:
methods: {
async getAllDivisions() {
try {
this.divisions = (await ApiService.getAllDivisions()).data
} catch (error) {
console.error(error)
}
}
},
Here is how I have my code set up in a file called DivisionEdit.vue
Template HTML:
<form #submit.prevent="onSubmitUpdate">
Division Name:
<input type="text" v-model="division.division" />
<button type="submit">
Update Division
</button>
</form>
Script section:
data() {
return {
division: {
division: '',
division_id: null
},
methods: {
onSubmitUpdate() {
ApiService.updateDivision(this.division)
}
}
And I have the api service code like so in apiService.js:
updateDivision(division) {
return this.getApiClient().put('/Divisions', division)
}
You already have all the divisions in the parent component, you can pass that as a props to child component
And in the child component before onSubmitUpdate, you can have two approaches here
1) you can disable the update button by default, and have validation
for the input division by adding #input event -> check division if
already exist, if not enable the button
<form #submit.prevent="onSubmitUpdate">
Division Name:
<input type="text" v-model="division.division" #input="divisionExists" />
<button type="submit" :disabled="btnDisable">
Update Division
</button>
</form>
In Script:
props: {
divisions: Object,
},
data() {
return {
division: {
division: '',
division_id: null
},
btnDisable: true,
}
}
methods: {
divisionExists() {
if (this.divisions.map(x => x.division).includes(this.division.division)){
this.btnDisable = true
} else {
this.btnDisable = false;
}
},
onSubmitUpdate() {
ApiService.updateDivision(this.division)
}
}
2) You can dirrectly add a condition in the onSubmitUpdate method to
check if the edit division is already exist it will not trigger update
api
onSubmitUpdate() {
if (!this.divisions.map(x => x.division).includes(this.division.division)){
ApiService.updateDivision(this.division)
}
}

Change Polymer 3 route to a different html page

I am creating a sample Polymer 3 app with a login and dashboard page. My backend is a simple JX-RS REST API. Once I get a response from the web service, I want to go to a new HTML file (lets says dashboard.html) rather than route to a different element within the same page. When I go through the
official website, I could not really understand how to proceed as I am a beginner in JS itself.
In my index.html, I have <my-login>, after the response, handlePositiveResponse is called. This is the place where I am changing the route. Please find the method below.
Following is my code:
login.js
class MyLogin extends PolymerElement {
static get template() {
return html`
<h1>Hello World..!!</h1>
<iron-form id="loginUserForm" on-iron-form-response="handlePositiveResponse" on-iron-form-error="handleNegativeResponse">
<form id="innerLoginUserForm" content-type="application/json" method="post">
<paper-input id="email" name="email" label="E-Mail Address"></paper-input>
<paper-input id="password" name="password" label="Password" type="password"></paper-input>
<paper-button disabled="{{activeRequest}}" raised id="loginButton" on-tap="submitLogin">Sign In</paper-button>
</form>
</iron-form>
`;
}
static get properties() {
return {
page: {
type: String,
reflectToAttribute: true,
observer: '_pageChanged'
},
routeData: Object,
subroute: Object
};
}
static get observers() {
return [
'_routePageChanged(routeData.page)'
];
}
_routePageChanged(page) {
// Show the corresponding page according to the route.
//
// If no page was found in the route data, page will be an empty string.
// Show 'view1' in that case. And if the page doesn't exist, show 'view404'.
if (!page) {
this.page = 'login';
} else if (['view1', 'view2', 'view3', 'my-dashboard'].indexOf(page) !== -1) {
this.page = page;
} else {
this.page = 'view404';
}
// Close a non-persistent drawer when the page & route are changed.
// if (!this.$.drawer.persistent) {
// this.$.drawer.close();
// }
}
_pageChanged(page) {
// Import the page component on demand.
//
// Note: `polymer build` doesn't like string concatenation in the import
// statement, so break it up.
switch (page) {
case 'view1':
import('./my-view1.js');
break;
case 'view2':
import('./my-view2.js');
break;
case 'view3':
import('./my-view3.js');
break;
case 'my-dashboard':
import('./my-dashboard.js');
break;
case 'view404':
import('./my-view404.js');
break;
}
}
submitLogin(e) {
var form = this.shadowRoot.querySelector('#loginUserForm');
this.shadowRoot.querySelector('#innerLoginUserForm').action = 'http://localhost:8080/PolymerJavaBackend/rest/login'
form.submit();
}
handlePositiveResponse(response) {
this._routePageChanged(null);
this._routePageChanged('my-dashboard');
console.log(response);
}
handleNegativeResponse(error) {
console.log(error);
}
Would appreciate, if you could advise, how to route to a new html page.
Is that your top-level element? Is in your top-level element, where you should have the iron-pages element with all the pages you have in your app, and where you must add the new page.
There you should have the _routePageChanged to check the route data changes. And _pageChanged to import the page.
If you want to navigate to your new page, not from menu, but when you'd get response from the server, in handlePositiveResponse(response), you can use the two-way databinding or this.set to update the route value: this.set('route.path', '/my-dashboard');

Categories