Resetting validation in vue - forms

here's the example of my simple form which throws an error when the text field is empty. On the first submit everything is ok, but after next you see the error before submitting second message. Here's code:
<div id="app">
<v-app >
<v-dialog v-model="dialog">
<template v-slot:activator="{ on }">
<v-btn v-on="on">Open</v-btn>
</template>
<v-card>
<v-text-field
v-model="note"
:rules="noteRules"
></v-text-field>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn #click="submit()">save</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-app>
</div>
and app.js
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
dialog: false,
note: '',
noteRules: [
v => !!v || 'error'
],
}),
methods: {
clear() {
this.dialog = false;
//something here?
}
}
})
how should I reset the validation? here's codepen https://codepen.io/tutu-kaen/pen/oNjPPKe

Wrap your content of the card in a v-form, add a v-model and a ref to that v-form.
You can then access that v-form in your clear() by using this.$refs..
The formValid will be a boolean so you can easily check if a form is valid by using if (this.formValid) anywhere in your code, for example to disable the send button.
Example:
<div id="app">
<v-app>
<v-dialog v-model="dialog">
<template v-slot:activator="{ on }">
<v-btn v-on="on">Open</v-btn>
</template>
<v-card>
<v-form v-model="formValid" ref="myForm">
<v-text-field v-model="note" :rules="noteRules"></v-text-field>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn #click="submit()">save</v-btn>
</v-card-actions>
</v-form>
</v-card>
</v-dialog>
</v-app>
</div>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
dialog: false,
note: '',
formValid: false,
noteRules: [
v => !!v || 'error'
],
}),
methods: {
submit() {
this.note = '';
this.dialog = false;
this.$refs.myForm.reset();
}
}
})
Codepen example

Related

VueJs submit multiple rows array in form

I have a form, which has a vue componenet that allows users to create additional input lines in the form.
I am having an issue getting all of these input lines to submit for the axios request, currently it only outputs the last added rows input.
Typically, in a normal PHP form, I would just make the field an array (name="MultiRow[]"), however I am lost at doing this in Vue and struggling to find any doc that covers this.
Here is the component in my form:
<div class="mt-5 md:mt-0 md:col-span-2">
<fieldset class="mt-6">
<div class="mt-6">
<response-set-input v-model="fields.response"></response-set-input>
</div>
</fieldset>
</div>
Here is my Vue File for form submission:
<script>
import Switch from '../../components/StatusToggle';
export default {
data() {
return {
fields: {},
errors: {},
statusToggle: false,
}
},
methods: {
toggled(toggleOn){
statusToggle: toggleOn
},
submit() {
this.errors = {};
axios.post('/submit', this.fields).then(response => {
alert('Message sent!');
}).catch(error => {
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});
},
},
components: {
statusToggle: Switch
}
}
</script>
Here is my component code:
<template>
<div>
<div class="m-2" v-for="(row, index) in rows" :key="index">
<div class="col-span-12 sm:col-span-3 mb-1">
<label for="responseTitle" class="block text-sm font-medium leading-5 text-gray-700">Response</label>
<input
id="responseTitle"
class="mt-1 form-input block w-full py-2 px-3 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:shadow-outline-blue focus:border-blue-300 transition duration-150 ease-in-out sm:text-sm sm:leading-5"
type="text"
name="fields.response[]"
:value="responseInput"
#input="onInput($event.target.value)"/>
</div>
<div class="mt-2">
<button type="button" class="inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs leading-4 font-medium rounded text-gray-700 bg-green-100 hover:bg-indigo-50 focus:outline-none focus:border-indigo-300 focus:shadow-outline-indigo active:bg-indigo-200 transition ease-in-out duration-150" #click="addRow">
Add new Response
</button>
<button type="button" class="inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs leading-4 font-medium rounded text-gray-700 bg-red-100 hover:bg-indigo-50 focus:outline-none focus:border-indigo-300 focus:shadow-outline-indigo active:bg-indigo-200 transition ease-in-out duration-150" #click="removeRow(index)">
Remove
</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['responseInput'],
data () {
return {
rows: [],
stopRemoval: true,
}
},
watch: {
rows () {
this.stopRemoval = this.rows.length <= 1
}
},
methods: {
onInput(responseInput){
this.$emit('input', responseInput),
console.log(responseInput)
},
addRow () {
let checkEmptyRows = this.rows.filter(row => row.number === null)
if (checkEmptyRows.length >= 1 && this.rows.length > 0) {
return
}
this.rows.push({
responseTitle: null,
})
},
removeRow (rowId) {
if (!this.stopRemoval) {
this.rows.splice(rowId, 1)
}
}
},
mounted () {
this.addRow()
}
}
</script>
How do I submit the multiple rows to the form submission with Vue?
There's a decent amount wrong with your code, I suggest that you read the documentation.
Just to name a few things:
You shouldn't update a prop in a component as it will get overridden when the parent updates, props: ['responseInput'], and :value="responseInput"
You're not passing any prop called responseInput, v-model passes a prop called value.
Vue is only reactive on properties that processed during instance initialisation and that means it doesn't know about response on fields: {},
You're using rows (which is good), but then you're only emitting the prop you passed in responseInput. I think :value="responseInput" is supposed to be :value="row"

Semantic UI Custom Rule Validation for Select Drop-Down Field

I am trying to add some custom logic to my semantic ui validation but can't figure out what I am doing wrong.
Basically, when the user selects "Yes" from the drop-down, I would like to make the "input_field" mandatory. If the user selects "No", the "input_field" becomes optional and the form can be submitted.
I tried searching for examples and followed some code from the Semantic Ui website but can't figure out what I am missing. Any advice would be appreciated as I am on a deadline for a project I am working on.
Form:
<div class="ui dimmer">
<div class="ui huge text loader">Loading</div>
</div>
<form method="post" action="" class="ui form" autocomplete="on">
<div class="ui segment">
<div class="ui two fields">
<div class='field'>
<div class="ui selection dropdown">
<input type="hidden" class="selectOption" name="select">
<i class="dropdown icon"></i>
<div class="default text">Select an option</div>
<div class="menu">
<div class="item" data-value="Yes">Yes</div>
<div class="item" data-value="No">No</div>
</div>
</div>
</div>
<div class="field">
<input id="input_field" name="input_field" type="text"/>
</div>
</div>
</div>
<button id="submit" class="ui green button" name="submit" type="submit">Submit</button>
</form>
Validation:
<script>
$('.ui.form').form({
keyboardShortcuts: false,
on: 'blur',
inline: 'true',
fields: {
selectOption: {
identifier: 'select',
rules: [
{
type: 'empty',
prompt: 'Please select an option'
}]
},
input_field: {
identifier: 'input_field',
depends: 'select',
rules: [
{
type: 'empty',
prompt: function() {
$('.select').on('change', function() {
if( this.value == 'Yes') {
return "Custom Validation";
}
return false;
}).trigger("change");
}
}]
}
},
onSuccess: function() {
$('.ui.dimmer').dimmer('show');
},
onFailure: function() {
event.preventDefault();
}
}
);
});
</script>
Figured out a solution for this! It might not be the best answer but it works and does what I am looking for.
<div class="ui dimmer">
<div class="ui huge text loader">Loading</div>
</div>
<form method="post" action="" class="ui form" autocomplete="on">
<div class="ui segment">
<div class="ui two fields">
<div class='field'>
<div class="ui selection dropdown">
<input type="hidden" class="selectOption" name="select">
<i class="dropdown icon"></i>
<div class="default text">Select an option</div>
<div class="menu">
<div class="item" data-value="Yes">Yes</div>
<div class="item" data-value="No">No</div>
</div>
</div>
</div>
<div class="field">
<input id="input_field" name="input_field" type="text"/>
</div>
</div>
</div>
<button id="submit" class="ui green button" name="submit" type="submit">Submit</button>
</form>
<script>
$('.ui.form').form({
keyboardShortcuts: false,
on: 'blur',
inline: 'true',
fields: {
selectOption: {
identifier: 'select',
rules: [
{
type: 'empty',
prompt: 'Please select an option'
}]
}
},
onSuccess: function() {
$('.ui.dimmer').dimmer('show');
},
onFailure: function() {
event.preventDefault();
}
}
);
$('.selectOption').on('change', function() {
if ( this.value == 'Yes' ) {
$('.ui.form').form('add rule', 'input_field', ['empty', 'integer']);
$('.ui.form').form('add prompt', 'input_field', 'Enter an integer');
}
if ( this.value == 'No' ) {
$('.ui.form').form('remove prompt', 'input_field');
$('.ui.form').form('remove rule', 'input_field');
}
}).trigger("change");
});
</script>
I was able to implement the validation rule by extending Semantic UI setting rules.
See below example:
$.fn.form.settings.rules.dependsOnFieldValue = function (value, dependFieldValue) {
var identifier = dependFieldValue.split('[')[0];
var dependValue = dependFieldValue.match(/\[(.*)\]/i)[1];
if( $('[data-validate="'+ identifier +'"]').length > 0 ) {
matchingValue = $('[data-validate="'+ identifier +'"]').val();
}
else if($('#' + identifier).length > 0) {
matchingValue = $('#' + identifier).val();
}
else if($('[name="' + identifier +'"]').length > 0) {
matchingValue = $('[name="' + identifier + '"]').val();
}
else if( $('[name="' + identifier +'[]"]').length > 0 ) {
matchingValue = $('[name="' + identifier +'[]"]');
}
return (matchingValue !== undefined)
? !( dependValue.toString() === matchingValue.toString() && value === '')
: false
;
};
Then in the form validation initializer you will pass the desired values as below:
$(".ui.form").form({
fields: {
select: {
identifier: 'select',
rules : [
{
type : 'empty'
}
]
},
input_field: {
identifier : 'input_field',
rules : [
{
type : 'dependsOnFieldValue[select[Yes]]',
}
]
},
...
}
});
Notice that we pass the <select> identifier (in this case also called select) within the first [] and then the value that we want to see to make the input_field mandatory ("Yes" in this case).

Reset form and validation

I have a problem with a dialog modal who don,t want to close even with a function
I have this code to reset and close the modal, the resetting is ok but nothing close with cancel, I use the resetForm() function
I have a form with this structure ( form and rules )
<template>
<div class="text-center">
<v-dialog
v-model="dialog"
>
<template v-slot:activator="{ on }">
<v-btn class="addGroup" v-on="on">Add a group</v-btn>
</template>
<v-form
ref="form"
v-model="valid"
lazy-validation
>
<v-card>
<v-card-title
class="headline grey lighten-2"
primary-title
>
Add a group
</v-card-title>
<v-stepper v-model="e1">
<v-stepper-header class="stepHeader">
<v-stepper-step :complete="e1 > 1" step="1">Choose a name</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step :complete="e1 > 2" step="2">Select fixtures</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step :complete="e1 > 3" step="3">Apply a recipe</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step :complete="e1 > 4" step="4" >Select dates</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step step="5">Summary</v-stepper-step>
</v-stepper-header>
<v-stepper-items>
<v-stepper-content step="1" class="mt-6">
<v-card
>
<div class="step chooseName">
<h3>Create a group</h3>
<p class="mt-12">Choose a name for your group</p>
<v-text-field
:rules="rules.name"
#keyup.enter="e1 = 2"
v-model="form.groupName"
></v-text-field>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 2"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="2" class="mt-6">
<v-card
>
<div class="step selectFixtures">
<h3><v-icon #click="e1 = 1">mdi-chevron-left</v-icon>Select fixtures</h3>
<p class="mt-12 mb-6"
>Choose fixtures you want associate with {{form.groupName}}.</p>
<v-select
:rules="rules.fixture"
v-model="form.selectedFixture"
:items="fixtures"
item-text="name"
></v-select>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 3"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="3" class="mt-6">
<v-card
flat
height="68vh"
rounded
>
<div class="step applyRecipe">
<h3><v-icon #click="e1 = 2">mdi-chevron-left</v-icon>Apply a recipe to your group</h3>
<p class="mt-12 mb-6">Select a recipe for the group {{groupName}}.</p>
<div class="selectRecipe">
<v-select
class="mr-6"
v-model="form.selectedRecipe"
:items="recipe"
item-text="name"
item-value="duration"
return-object>
</v-select>
<p>or</p>
<create_recipe></create_recipe>
</div>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 4"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="4" class="mt-6">
<v-card
>
<div class="selectDates">
<h3><v-icon #click="e1 = 3">mdi-chevron-left</v-icon>Select start date</h3>
<p class="mt-6">Select the launch date of the Tuscan sun recipe for the {{groupName}} group</p>
<p>The end date will be set automatically according to the parameters of your recipe</p>
<v-date-picker
class="mt-6 ml-6"
v-model="selectedDate"
no-title
:date-format="date => new Date(date).toDateString()"
>
</v-date-picker>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 5"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="5" class="mt-6">
<v-card
>
<div class="stepChooseName">
<h3><v-icon #click="e1 = 4">mdi-chevron-left</v-icon>Summary</h3>
<p class="answer">Group name :</p>
<p class="subtitle">{{form.groupName}}</p>
<v-divider></v-divider>
</div>
</v-card>
<v-btn
#click="submit()"
>
Add group
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
</v-stepper-items>
</v-stepper>
</v-card>
</v-form>
</v-dialog>
</div>
</template>
I have this code to reset and close the modal, the resetting is ok but nothing close with cancel, I use the resetForm() function
I have a form with this structure ( form and rules )
<script>
import Create_recipe from "./create_recipe";
export default {
components: {Create_recipe},
props: ['groups', 'fixtures'],
groups: [],
data() {
const defaultForm = Object.freeze({
groupName: '',
selectedFixture: [],
selectedRecipe: '',
selectedScenario: '',
});
return {
form: Object.assign({}, defaultForm),
valid: true,
rules: {
name: [val => (val || '').length > 0 || 'This field is required'],
fixture: [val => (val || '').length > 0 || 'fixture is required'],
recipe: [val => (val || '').length > 0 || 'recipe is required'],
},
dialog: null,
defaultForm,
e1:0,
counterOfUnnamed:'',
checkbox: true,
fixtures: this.fixtures,
selectedDate: new Date().toISOString().substr(0, 10),
recipe: [{
id:1,
name: 'Tuscan sun',
duration: '5',
},
{ id:2,
name: 'Montreal summer',
duration: '10',
},
{ id:3,
name: 'French spring',
duration: '365',
}
],
}
},
methods: {
numberOfFixture() {
return this.form.selectedFixture.length;
},
resetForm () {
this.$refs.form.reset();
this.dialog = false
},
submit() {
if (!this.form.groupName) {
this.form.groupName = "Unnamed" + this.counterOfUnnamed;
this.counterOfUnnamed = this.counterOfUnnamed + 1;
this.counterOfUnnamed = parseInt(this.counterOfUnnamed);
}
var self = this;
http.post('group/create', {
name: self.form.groupName,
}).then((result) => {
self.groups.push(result);
self.resetForm();
})
},
},
computed: {
displayFixturesName() {
return this.form.selectedFixture.join(', ');
},
formIsValid() {
return (
this.form.selectedFixture &&
this.form.selectedRecipe
)
}
}
}
</script>
```
But when I launch the reset function, the form is reset but the validation appears.
How can I solve it ?
In your case use this.$refs.form.resetValidation() for reset the validation after reset
resetForm () {
this.$refs.form.reset()
this.$refs.form.resetValidation()
},
Here is the working code
Codepen link: https://codepen.io/chansv/pen/QWWExBz?editors=1010
<div id="app">
<v-app id="inspire">
<v-form
ref="form"
v-model="valid"
>
<v-text-field
v-model="formObj.name"
:counter="10"
:rules="nameRules"
label="Name"
required
></v-text-field>
<v-text-field
v-model="formObj.email"
:rules="emailRules"
label="E-mail"
required
></v-text-field>
<v-btn
:disabled="!valid"
color="success"
class="mr-4"
#click="submitForm"
>
Submit
</v-btn>
<v-btn
color="error"
class="mr-4"
#click="reset"
>
Reset Form
</v-btn>
</v-form>
</v-app>
</div>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data() {
const defaultForm = Object.freeze({
name: '',
email: '',
})
return {
formObj: Object.assign({}, defaultForm),
valid: true,
nameRules: [
v => !!v || 'Name is required',
v => (v && v.length <= 10) || 'Name must be less than 10 characters',
],
emailRules: [
v => !!v || 'E-mail is required',
v => /.+#.+\..+/.test(v) || 'E-mail must be valid',
],
};
},
methods: {
submitForm () {
console.log(this.formObj);
},
reset () {
this.$refs.form.reset();
console.log(this.formObj);
},
},
})
If you are reseting the form , no need to set default value this.form = Object.assign({}, this.defaultForm)
This reset function automatically resets all the value in the form this.$refs.form.reset()

Vuetify: How to fix v-date-picker not showing the chosen date in the text-field

I'm creating a form with vue.js / vuetify 2, one of the field is Date Event, so I used v-date-picker for the user to choose the date. The problems are the following:
Date Picker menu opens, but cannot pick date. If any dates were clicked, it won't update the menu. The months and years can be changed (UI), but still doesn't update.
With the above problem, the text-field remains empty.
I tried updating vuetify from version 1.5 to the latest version 2, and the problem still persists. I am using date-fns to format the date, so I tried to change the value of v-text-field = "formattedDate" into v-text-field = "date"
After a hot reload (not a refresh, F5, the page hotloaded itself), the date appeared in the form, but still date cannot be changed in the menu (clicking other dates does nothing).
<template>
<v-app>
<v-content>
<v-layout wrap row mt-2 align-center justify-center>
<v-card width="1050px" height= "690px">
<v-card-title class="display-1 font-weight-medium ">Post-Event Form:</v-card-title>
<v-form>
<v-container>
<v-layout row wrap>
<v-flex md4>
<v-text-field v-model="event" prepend-icon="event" label="Event Name" required></v-text-field>
</v-flex>
<v-flex md3>
<v-menu>
<v-text-field :value="formattedDate" slot="activator" label="Date of event" prepend-icon="date_range"></v-text-field>
<v-date-picker v-model="date"></v-date-picker>
</v-menu>
</v-container>
</v-flex>
</v-form>
</v-content>
</v-app>
</template>
<script>
import format from 'date-fns/format'
export default{
data() {
return {
evenum: int,
event: '',
// date: '',
date: new Date().toISOString().substr(0, 10),
menu1: true,
menu2: true,
}
},
computed: {
formattedDate() {
return this.date ? format(this.date, 'do MMM YYYY') : ''
},
},
}
</script>
I expect to have a functional v-date-picker, a menu that can be interacted with (click / choose date) which then updates the text-field and show the updated date.
Actual results were that of the menu opens yet cannot pick the date, and no update is seen in the text-field.
Try this:
<template>
<v-menu
v-model="showPicker"
:close-on-content-click="false"
transition="scale-transition"
offset-y
full-width
max-width="290px"
min-width="290px"
>
<template v-slot:activator="{ on }">
<v-text-field
v-model="selectedDate"
label="Choose the date"
hint="YYYY/MM/DD"
persistent-hint
readonly
v-on="on"
></v-text-field>
</template>
<v-date-picker
v-model="selectedDate"
no-title
#input="showPicker = false"
></v-date-picker>
</v-menu>
</template>
<script>
export default {
data: () => ({
showPicker: false,
selectedDate: null,
})
</script>
It is extracted from my code that is working as we speak.
Working example: Codepen
Try this : you can use v-model instead :value
<div id="app">
<v-app id="inspire">
<v-container>
<v-row>
<v-col cols=12 md="4">
<v-menu
v-model="showPicker"
:close-on-content-click="false"
:nudge-right="40"
transition="scale-transition"
offset-y
min-width="290px"
max-width="290px"
>
<template v-slot:activator="{ on }">
<v-text-field
v-model="selectedDate"
label="date"
prepend-icon="mdi-calendar-range"
readonly
v-on="on"
></v-text-field>
</template>
<v-date-picker v-model="date" #input="closeDateMenu"></v- date-picker>
</v-menu>
</v-col>
</v-row>
</v-container>
</v-app>
</div>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
showPicker: false,
selectedDate: null,
date:null,
}),
methods:{
closeDateMenu (){
this.showPicker = false;
this.selectedDate= this.date ? moment(this.date).format('dddd, MMMM Do YYYY') : '';
},
}
})
Working example : Codepen
This is how I fixed the date picker for my project.
<template>
<v-flex>
<v-menu
ref="menu2"
v-model="menu2"
:close-on-content-click="false"
:return-value.sync="date"
transition="scale-transition"
offset-y
min-width="auto">
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-model="selectDate"
placeholder="DD/MM/YYYY"
readonly
v-bind="attrs"
v-on="on">
<template v-slot:prepend-inner>
<v-icon> mdi-calendar </v-icon>
</template>
</v-text-field>
</template>
<v-date-picker
v-model="selectDate"
scrollable
<v-spacer></v-spacer>
<v-btn text color="primary" #click="menu2 = false">
Cancel
</v-btn>
<v-btn text
#click="$refs.menu2.save(selectDate)">
OK
</v-btn>
</v-date-picker>
</v-menu>
</v-flex>
</template>
<script>
export default {
data() {
return {
selectDate: "",
menu1: false,
};
},
};
</script>

Getting a "FB.login() called before FB.init()." when I run this code locally,

I can't seem to be able to login to my app that I'm making when I click on my "Log in with Facebook" button. Also, I'm using React JS. I think it might have something to do with not having REACT_APP_FACEBOOKLOGIN=######### (where ######### is my Facebook Developer ID) inside of a .env file.
import React, { Component } from 'react';
import logo from './logo.png';
import FacebookLogin from 'react-facebook-login';
import Sidebar from "react-sidebar";
import LeaveGroup from "./components/LeaveGroup";
// import firebase from "./utils/firebase.js";
import { GoogleApiWrapper } from 'google-maps-react';
import MapBox from "./components/MapBox";
// import ReactDOM from 'react-dom'
import ChatBox from "./components/ChatBox";
import API from "./utils/API";
import './App.css';
import CreateGroup from './components/CreateGroup/CreateGroup';
require("dotenv").config();
class App extends Component {
constructor(props) {
super(props);
this.state = {
sidebarOpen: true,
name: "",
id: "",
chatText: "",
messagesArray: [],
groupName: "",
};
this.onSetSidebarOpen = this.onSetSidebarOpen.bind(this);
}
onSetSidebarOpen(open) {
this.setState({ sidebarOpen: open });
};
componentDidMount() {
this.loadUsers();
}
loadUsers = () => {
API.getUsers()
.then(res =>
this.setState({ users: res.data }, () => console.log("loadUsers Data: ", res.data))
)
.catch(err => console.log(err));
};
saveUsers = (data) => {
API.saveUser(data)
.then(res =>
console.log(res))
}
handleOnClick = event => {
event.preventDefault();
if (this.state.name) {
API.saveUser({
name: this.state.name,
})
.then(res => this.loadUsers())
.catch(err => console.log(err));
}
};
responseFacebook = (response) => {
console.log(response);
this.setState({ name: response.name, id: response.id })
this.saveUsers(response);
}
render() {
return (
<div className="App">
<Sidebar
sidebar={<b>
<button onClick={() => this.onSetSidebarOpen(false)}>
×
</button>
<div>
<img id="logo-image" src={logo} alt="catchup-app-logo" />
</div>
<div className="about-text">
{/* <p>The CatchUp! app allows you to
create, share and join private location based groups.
</p> */}
</div>
<div
style={{ padding: 40 }}>
<br />
<FacebookLogin
appId={process.env.REACT_APP_FACEBOOKLOGIN}
autoLoad={true}
reauthenticate={true}
fields="name,email,picture"
callback={this.responseFacebook}
/>
<br />
<br />
</div>
{/* Create group box */}
<CreateGroup
groupName={this.state.groupName}
groupMember={this.state.name}
/>
{/* Join group box */}
<div className="text-box">
<p>
<button class="btn btn-dark" type="button" data-toggle="collapse" data-target="#collapseExample1" aria-expanded="false" aria-controls="collapseExample">
Join a Group
</button>
</p>
<div class="collapse" id="collapseExample1">
<div class="card card-body">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Group Name" aria-label="Group Name" aria-describedby="button-addon2" />
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="button-addon">Join</button>
</div>
</div>
</div>
</div>
</div>
<ChatBox
name={this.state.name}
groupName={this.state.groupName}
messagesArray={this.state.messagesArray}
/>
</b>}
open={this.state.sidebarOpen}
onSetOpen={this.onSetSidebarOpen}
styles={{ sidebar: { background: "white" } }}
>
<button onClick={() => this.onSetSidebarOpen(true)}>
<i class="fas fa-bars"></i>
</button>
</Sidebar>
<br />
<br />
<MapBox
gProps={this.props.google}
gZoom={17}
gOnMarkerClick={this.gOnMarkerClick}
gName={this.state.name}
gGroupName={this.state.groupName}
gOnClose={this.onInfoWindowClose}
/>
</div>
);
}
}
export default GoogleApiWrapper({
apiKey: `${process.env.REACT_APP_GOOGLE_MAPS_API_KEY}`
})(App)
I want this to be able to get this to work so move onto logging in a user into my MongoDB.