Onclick event not changing this.state.value2 variable - reactjs

when the weather details are displayed after search, clicking on the image is supposed to append the details and display the retVal in the handleClick event. For some reason this.setState for value2 is not even changing the variable and keeping it null.Ive tried converting to async thinking that maybe setState hadnt been finished by the time the page rendered but that didnt work either.
class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
city: "",
temp: 0,
feels: "",
w_status: "",
description: "",
condition: "",
max: 0,
min: 0,
wind_speed: 0,
humidity: "",
pressure: 0,
sunrise: 0,
lastUpdate: "",
image: "",
value1: null,
value2: "Value 2 is currently null",
activate_err: false,
};
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleClick(e) {
console.log("handle click is being called");
const retval = (
<div>
<p>Maximum Temprature: {this.state.max}</p>
<p>Minimum Temprature: {this.state.min}</p>
<p>Humidity: {this.state.humidity}</p>
<p>Wind Speed: {this.state.wind_speed}</p>
<p>Pressure: {this.state.pressure}</p>
<p>Sunrise: {this.state.sunrise}</p>
</div>
);
if(this.state.value2 != null){
this.setState({ value2: null});
console.log("It is hidden");
}
else{
this.setState({ value2: retval});
console.log("It is shown");
}
}
async handleSubmit(e) {
const search = e.target.SearchVal.value;
console.log("You entered " + search);
console.log("Time to modify the entry!");
e.preventDefault();
//Converts any string with extra spaces to one space in between
console.log(search.replace(/\s{2,}/g, " ").trim());
const results = search
.replace(/\s{2,}/g, " ")
.trim()
.split(" ");
await fetch(
"https://api.openweathermap.org/data/2.5/weather?q=" +
results +
"&appid=" +
KEY
)
.then((response) => response.json())
.then((data) => {
console.log(data);
if (data["cod"] != 200) {
console.log(
"Error during search, activate err has been set to true!"
);
this.setState({ activate_err: true });
} else {
this.setState({
city: data["name"],
temp: data["main"]["temp"],
feels: data["main"]["feels_like"],
w_status: data["weather"][0]["main"],
description: data["weather"][0]["description"],
max: data["main"]["temp_max"],
min: data["main"]["temp_min"],
wind_speed: data["wind"]["speed"],
humidity: data["main"]["humidity"],
pressure: data["main"]["pressure"],
sunrise: data["sys"]["sunrise"],
image:
"http://openweathermap.org/img/wn/" +
data["weather"][0]["icon"] +
"#2x.png",
activate_err: true,
});
const retval = (
<div>
<hr />
<div className="weather-card">
<h3>City: {this.state.city}</h3> <img onClick={() => this.handleClick()} src={this.state.image} />
<h3>
Temprature: {this.state.temp} Feels Like: {this.state.feels}
</h3>
<p>{this.state.w_status}</p>
<p>{this.state.description}</p>
<div id="details" className="weather-details">
{this.state.value2}
</div>
</div>
<hr />
</div>
);
this.setState({ value1: retval });
}
})
.catch((err) => {
console.log(err);
});
if (this.state.activate_err == false) {
}
/*
let status = true;
let activate = false;
let i = 0;
while(status){
if(result[i] == ' ')
status = false;
if(activate){
}
}
status = true;
*/
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="search"
placeholder="Enter a city, country or country code!"
name="SearchVal"
/>
<input type="submit" value="Search" />
</form>
<div id="search-results">{this.state.value1}</div>
</div>
);
}
}

Related

How do I search data with pagination in React?

class Employee extends Component {
constructor() {
super();
this.state = {
// employees: employees,
employees: [],
searchfield: "",
currentPage: 1,
resultsPerPage: 50,
holder: [],
filteredEmployees: [],
value: "",
};
}
componentDidMount = async () => {
axios.get(`http://localhost:5000/`).then((res) => {
const employees = res.data;
this.setState({
employees: employees.recordsets[0],
holder: employees.recordsets[0],
});
});
};
onSearchChange = (event) => {
let { value } = event.target;
this.setState({ value }, () => {
var updatedList = this.state.holder;
updatedList = updatedList.filter((employee) => {
const fullName = employee.empFirstNm + " " + employee.empLastNm;
return (
fullName.toLowerCase().search(this.state.value.toLowerCase()) !== -1
);
});
this.setState({ employees: updatedList });
});
};
//change page
onPaginate = (pageNumber) => {
this.setState({ currentPage: pageNumber });
};
render() {
const { employees, searchfield, currentPage, resultsPerPage } = this.state;
const { onRouteChange } = this.props;
//Get current employees
const indexOfLastEmployee = currentPage * resultsPerPage;
const indexOfFirstEmployee = indexOfLastEmployee - resultsPerPage;
console.log("indexOfFirstEmployee: ", indexOfFirstEmployee);
console.log("indexOfLastEmployee: ", indexOfLastEmployee);
const filteredEmployees = employees.slice(
indexOfFirstEmployee,
indexOfLastEmployee
);
return !employees.length ? (
<div className="tc">
<h1>Loading</h1>
<Spinner animation="border" variant="danger" />
</div>
) : (
<FadeIn>
<div className="tc">
<div
className="
d-flex
justify-content-between
flex-wrap
flex-md-nowrap
align-items-center
pt-3
pb-2
mb-3
border-bottom"
>
<h1 className="display-2">Employees</h1>
<div
className="tr"
style={{
margin: "15px 0",
}}
>
<NewEmployee employees={employees} />
<SearchBox
searchChange={this.onSearchChange}
value={this.state.value}
/>
</div>
</div>
<Scroll>
<CardList
employees={filteredEmployees}
onDelete={this.handleDelete}
onRouteChange={onRouteChange}
/>
<Table
employees={filteredEmployees}
onRouteChange={onRouteChange}
/>
<Pagination
resultsPerPage={resultsPerPage}
totalResults={employees.length}
onPaginate={this.onPaginate}
/>
</Scroll>
</div>
</FadeIn>
);
}
}
I have tried implementing it with conditions of whether the results
is greater than or equal to the results on a page but it did not
work since it doesnt cover every single case based on the result.
I am getting the search to work but when my current page is anything besides 1 is when the search doesn't work.
Any idea how I can get the filtering to work regardless of what page I
am on?
Figured this out. I just needed to set currentPage to 1 at the end of my search:
onSearchChange = (event) => {
let { value } = event.target;
this.setState({ value }, () => {
//running this after setting the value in state because of async
var updatedList = this.state.holder;
updatedList = updatedList.filter((employee) => {
const fullName = employee.empFirstNm + " " + employee.empLastNm;
return (
fullName.toLowerCase().search(this.state.value.toLowerCase()) !== -1
);
});
this.setState({ employees: updatedList });
this.setState({ currentPage: 1 });
});

How to Send message by just clickiing on the suggestion in Botframework-Webchat?

I want my bot to send the message when i click on the desired suggestion. i.e. i want the message to be sent - when i click on the suggestion or by selecting the suggestion using arrow keys and then pressing enter . But as of now, if i click or select the suggestion using arrow keys - the suggestion value comes to the text box and then i have to press enter to send the message. I just want to change that.
Any help would be greatly appreciated
My code is as follows,
import React from 'react';
import { DirectLine, ConnectionStatus } from 'botframework-directlinejs';
import ReactWebChat from 'botframework-webchat';
import './ChatComponent.css';
var val;
var apiParameters = [];
var currentFocus = -1;
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
token: '',
conversationId: '',
directLine: {},
view: false,
feedBack: null,
value: '',
popupContent: '',
storeValue: '',
suggestions: [],
suggestionCallback: '',
suggestionTypedText: "",
typingChecking: "false",
};
this.handleTokenGeneration = this.handleTokenGeneration.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSaveFeedback = this.handleSaveFeedback.bind(this);
this.handleSuggestion = this.handleSuggestion.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleSuggestionClick = this.handleSuggestionClick.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.moveHighlight = this.moveHighlight.bind(this);
this.getSuggestionHtml = this.getSuggestionHtml.bind(this);
}
getSuggestionHtml(suggestion) {
const lowerCaseSuggestion = suggestion.toLowerCase();
return {
__html: lowerCaseSuggestion.includes(this.state.suggestionTypedText) ? lowerCaseSuggestion
.replace(this.state.suggestionTypedText, `<b>${this.state.suggestionTypedText}</b>`) : lowerCaseSuggestion
};
}
handleTokenGeneration = async () => {
console.log("11111");
const response = await fetch(`api/TokenGenerationService/GetToken`);
const data = await response.json();
this.setState({ token: data.categoryObject.token, conversationId: data.categoryObject.conversationId });
this.state.directLine = new DirectLine({ token: this.state.token });
this.setState({ view: true });
this.setState({ typingChecking: "true" });
console.log("conversationId");
};
async handleSuggestion(val, store) {
if (val === "") {
this.setState({
suggestions: []
});
}
else {
apiParameters = [];
var valuess = null;
const response = await fetch(`api/TokenGenerationService/GetAzureSearch?myparam1=${val}`);
const data = await response.json();
var values = ["Hello", "yes", "no", "exit", "Welcome", "Thank You", "Approve", "Apply leave", "Reject", "Absence Balance", "Leave Balance", "Upcoming Holidays", "Apply Comp-Off", "Approve Leave", "Raise Incident Tickets", "Project Allocation Info", "Reporting Manager Change", "Reporting Manager Approval", "Approve Isolve Tickets", "My Manager", "My Account Manager", "Generate Salary Certificate", "Isolve Ticket Status", "Internal Job Posting", "My Designation", "My Joining Date", "RM Approval", "RM Change", "Resource Allocation", "ESettlement Approval", "SO Approval", "Cash advance Approval", "Purchase Request Approval", "Referral status", "HR Ticket", "Platinum Support"];
valuess = values.filter(s =>
s.toLocaleLowerCase().startsWith(val.toLowerCase())
);
valuess = valuess.concat(data.az_search);
this.setState({
suggestions: valuess,
suggestionCallback: store,
suggestionTypedText: val.toLowerCase()
});
var totCount = data.az_search;
console.log("kkkkkk" + totCount);
var myNode = document.getElementById('Suggestion1');
}
}
getSuggestionCss(index) {
var HIGHLIGHTED_CSS = "HIGHLIGHTED_CSS";
var SUGGESTION_CSS = "SUGGESTION_CSS";
console.log("jioouu" + this.state.highlightedIndex);
return index === this.state.highlightedIndex ? HIGHLIGHTED_CSS : SUGGESTION_CSS;
}
moveHighlight(event, direction) {
event.preventDefault();
const { suggestions, highlightedIndex=-1 } = this.state;
if (!suggestions.length) return;
let newIndex = (highlightedIndex + direction + suggestions.length) % suggestions.length;
console.log("lokkkk" + direction)
if (newIndex !== highlightedIndex) {
console.log("kkkkkkkkkkkkkkkkkkk")
this.setState({
highlightedIndex: newIndex,
});
}
}
keyDownHandlers = {
ArrowDown(event) {
this.moveHighlight(event, 1);
},
ArrowUp(event) {
this.moveHighlight(event, -1);
},
Enter(event) {
const { suggestions } = this.state;
if (!suggestions.length) {
// menu is closed so there is no selection to accept -> do nothing
return
}
event.preventDefault()
this.applySuggestion(suggestions[this.state.highlightedIndex]);
},
}
handleKeyDown(event)
if (this.keyDownHandlers[event.key])
this.keyDownHandlers[event.key].call(this, event)
}
async handleSuggestionClick(event) {
await this.applySuggestion(event.currentTarget.textContent);
}
async applySuggestion(newValue) {
await this.setState({ typingChecking: "false", suggestions: [], highlightedIndex: 0 });
this.state.suggestionCallback.dispatch({
type: 'WEB_CHAT/SET_SEND_BOX',
payload: {
text: newValue,
}
});
await this.setState({ typingChecking: "true" });
}
handleClose(elmnt) {
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt !== x[i]) {
x[i].parentNode.removeChild(x[i]);
}
}
}
async componentDidMount() {
try {
await this.handleTokenGeneration();
const store =
window.WebChat.createStore(
{},
({ getState }) => next => action => {
this.state.directLine.connectionStatus$
.subscribe(connectionStatus => {
//console.log("connect" + connectionStatus);
//console.log("LOP" + ConnectionStatus.ExpiredToken);
if (connectionStatus === ConnectionStatus.ExpiredToken) {
console.log("expired");
}
if (action.type === 'WEB_CHAT/SET_SEND_BOX') {
const val = action.payload.text;
if (this.state.typingChecking === "true") {
this.setState({
highlightedIndex: -1,
});
console.log(this.state.typingChecking);
this.handleSuggestion(val, store);
}
}
if (action.type === 'DIRECT_LINE/DISCONNECT_FULFILLED') {
console.log("final" + connectionStatus);
console.log("finalexpired" + ConnectionStatus.ExpiredToken);
console.log("final");
this.handleTokenGeneration();
// fetch('api/TokenGenerationService/GetToken').then(conversation => this.state.directLine.reconnect(conversation))
}
});
return next(action)
}
);
this.setState({ storeValue: store });
} catch (error) {
console.log("error in fetching token");
console.log(error);
}
this.state.directLine.activity$
.filter(activity => activity.type === 'message')
.subscribe(function (activity)
{
//console.log("oooooooooooooooooooooo");
}
// message => console.log("received message ", message.text)
);
}
handleSaveFeedback(ans) {
var userID = "U92656";
var feedbackmsg = this.state.value;
var feedbacktype = this.state.feedBack;
var convId = this.state.conversationId;
fetch('api/Feedback/SaveFeedback',
{
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ Uid: userID, FeedbackMessage: feedbackmsg, Convid: convId, FeedbackType: feedbacktype })
}).
then(response => response.text())
.then(data => {
console.log(data.getResult);
});
this.setState({ value: '' });
}
feedback(ans) {
this.setState({ feedBack: ans });
if (ans === "Send") {
this.handleSaveFeedback(ans);
}
else if (ans === "Yes") {
this.setState({ popupContent: "How was your experience?" });
// console.log(this.state.value)
}
else if (ans === "No") {
this.setState({ popupContent: "What went wrong?" });
// console.log(this.state.value)
}
}
handleChange = (event) => {
this.setState({ value: event.target.value });
}
render() {
if (!this.state.view) {
return <div />
} else {
const filteredSuggestions = this.state.suggestions.filter(
suggestion =>
suggestion.toLowerCase().indexOf(this.state.suggestionTypedText.toLowerCase()) > -1
);
return (
<div className="react-container webchat" >
<div onKeyDown={this.handleKeyDown.bind(this)}>
<div >
<ReactWebChat directLine={this.state.directLine} webSocket={true} userID='U92656' username='Thomas' store={this.state.storeValue} sendTypingIndicator={true} />
</div>
</div>
<div className="SuggestionParent" id="Suggestion1">
{this.state.suggestions.map((suggestion, index)=> (
<div className={this.getSuggestionCss(index)} key={index} onClick={this.handleSuggestionClick} >
{suggestion
.toLowerCase()
.startsWith(this.state.suggestionTypedText) ? (
<div>
<b>{this.state.suggestionTypedText}</b>
{suggestion
.toLowerCase()
.replace(this.state.suggestionTypedText, "")}
</div>
) : (
<div dangerouslySetInnerHTML={this.getSuggestionHtml(suggestion)} />
)}
</div>
))}
</div>
<footer className="chat-footer" >
<div className="foot-footer">
Was I helpful ?
<span className="feedback" onClick={() => this.feedback("Yes")} >Yes</span><span>|</span><span className="feedback" onClick={() => this.feedback("No")}>No</span>
{
this.state.feedBack === "Yes" || this.state.feedBack === "No" ?
(
<div className="dialog" id="myform">
<div id="textfeedback">
<span id="closeFeedback" onClick={() => this.feedback("Close")}>X</span>
<p>{this.state.popupContent}</p>
<input type="text" id="feedbacktxtbox" required name="textfeedback" placeholder="Pleasure to hear from u!"
onChange={this.handleChange}
value={this.state.value} />
<button type="button" id="btnfeedback" onClick={() => this.feedback("Send")}>send</button>
</div>
</div>
) : null
}
</div>
</footer>
</div>
);
}
}
}

React: loop through array response does not work

I run an axios get request to an Express server to get some dummy data:
customers = [
{ id: 1, firstName: "John" },
{ id: 2, firstName: "Brad" },
{ id: 3, firstName: "Mary" }
];
the data that is returned is determined by a user input: if the user enters "Brad", the result being returned will be { id: 2, firstName: "Brad" }.
For some reason, when I loop through the data returned, nothing works. Looking into the React Chrome Extension, the State returned is as follows:
{
"firstName": "Brad",
"id": 0,
"customers": [],
"res": []
}
Because I am learning React, I will post the whole component for you to see, perhaps the problem is something I don't see yet as a newbie:
class App extends Component {
constructor(props) {
super(props);
this.state = {
firstName: "",
id: 0,
customers: []
};
this.getName = this.getName.bind(this);
}
onChange = e => {
e.preventDefault();
this.setState({ firstName: e.target.value });
};
getName = e => {
e.preventDefault();
axios
.get("/api/customers", {
params: {
firstName: this.state.firstName
}
})
.then(res => {
console.log(res);
this.setState({ res: this.state.customers });
});
};
componentDidMount() {}
render() {
//if (!this.state.customers.length) return "Data not available yet";
return (
<div>
<h2>Customers</h2>
<div className="card card-body mb-4 p-4">
<div className="h1 display-4 text-center">
<h1 className="i fas">Search for a customer</h1>
<p className="lead text-center">Get the Customer's Name Here</p>
<form onSubmit={this.getName}>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="customer name ..."
name="firstName"
value={this.state.firstName}
onChange={this.onChange}
/>
</div>
<button
className="btn btn-primary btn-lg-block mb-5"
type="submit"
>
Get Customer
</button>
</form>
</div>
</div>
This is where I loop throuhg the data:
{this.state.customers.map(item => (
<li key={item.id}>{item.firstName}</li>
))}
</div>
);
}
}
And here is the Express route I'm calling:
app.get("/api/customers", (req, res) => {
let { firstName } = req.query;
const customers = [
{ id: 1, firstName: "John" },
{ id: 2, firstName: "Brad" },
{ id: 3, firstName: "Mary" }
];
console.log("the customer's name is " + firstName);
var str = customers.filter(x => x.firstName == firstName);
res.json(str);
});
So What I want is to display the data in a element below the input bar.
Try :
this.setState({ customers : res });
instead of :
this.setState({ res: this.state.customers });
Also, try to use React Hooks in order to refactor your code.

Save data to firebase

enter image description here
I am building this meeting booking app where the available meetings to books shows as buttons and after klicking the meeting you want so select. I want to make it possible to save that information in the button with a name and email that is written in the form.
I am having it hard to set the code so that my button selection is saved and saved to firebase along with the name and email after submit button is pressed. Right know I get the error that 'set' in handleSubmit is not set.
import React, { Component } from "react";
import "./App.css";
import firebase from "firebase";
const uuid = require("uuid");
class App extends Component {
constructor(props) {
super(props);
this.state = {
uid: uuid.v1(),
meeting: "",
name: "",
email: ""
};
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
// console.log(firebase);
var database = firebase.database();
var ref = database.ref("meeting");
var data = {
id: "",
user: ""
};
ref.push(data);
// this.state = {
// items: [],
// isLoaded: true,
// }
// this.state = {
// name: '',
// email: '',
// };
}
handleClick = e => {
console.log(e.target.innerHTML);
alert("Du har valt ett möte");
};
componentDidMount() {
fetch("http://www.mocky.io/v2/5c9cdca03300004d003f2151")
.then(res => res.json())
.then(json => {
let meetings = [];
json.forEach(meeting => {
if (
new Date(meeting.startDate).getDay() !==
new Date(meeting.endDate).getDay()
) {
let day1 = {
activity: meeting.activity,
location: meeting.location,
startDate: meeting.startDate
};
let day2 = {
activity: meeting.activity,
location: meeting.location,
endDate: meeting.endDate
};
meetings.push(day1, day2);
} else {
meetings.push(meeting);
}
});
console.log(meetings);
this.setState({
isLoaded: true,
items: meetings
});
});
firebase
.database()
.ref(`Newdata/${this.state.uid}`)
.on("value", snap => console.log("from db", snap.val()));
}
handleChange(e) {
this.setState({
name: e.target.name
});
}
handleSubmit(e) {
alert("Er bokning är bekräftad: " + this.state.value);
console.log("Du har bekräftat er bokning");
e.preventDefault();
firebase.database().ref(`Newdata/${this.state.uid}`);
set({
meeting: this.state.meeting,
name: this.state.name,
email: this.state.email
}).catch(error => console.log(error));
}
inputData(e) {
const meeting = this.refs.meeting1.value;
const name = this.refs.name1.value;
const email = this.refs.email1.value;
this.setState({ meeting, name, email });
}
render() {
var { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<>
<div className="App">
<div className="AppHeader">
<h1>Boka ditt möte nedan</h1>
</div>
<ul>
{items.map((item, i) => (
<li key={i}>
<button
onClick={e => this.handleClick(e)}
onChange={this.inputData}
className="select"
>
{item.activity}
<br />
Starttid: {item.startDate}
<br />
Sluttid: {item.endDate}
<br />
Plats: {item.location}
<br />
</button>
</li>
))}
</ul>
</div>
<div className="selectedMeeting">
Fyll i dina uppgifter och bekräfta
</div>
<form onSubmit={this.handleSubmit} className="bookingSection">
<label>
Name:
<input
type="text"
name={this.state.name}
onChange={this.inputData}
onChange={this.handleChange}
ref="name1"
/>
</label>
<label>
E-mail:
<input
type="text"
email={this.state.email}
onChange={this.inputData}
onChange={this.handleChange}
ref="email1"
/>
</label>
<input className="confirm" type="submit" value="Bekräfta" />
</form>
<div className="viewSelect" />
</>
);
}
}
}
export default App;
TL;DR;
You have a typo in your code, it should be:
firebase.database().ref('Newdata/${this.state.uid}').set({
meeting: this.state.meeting,
name: this.state.name,
email: this.state.email
}).catch(error => console.log(error));
Explanation:
Since you add the ;, you end the first expression and start a new one that is:
set({
meeting: this.state.meeting,
name: this.state.name,
email: this.state.email
}).catch(error => console.log(error));
Since there is no function defined, Javascript gives this error. But what you want do do is call the method set of the object firebase.database().ref('Newdata/${this.state.uid}'), therefore you should do:
firebase.database().ref('Newdata/${this.state.uid}').set({ /* ... */ })

Cant text in input field

I am building a meeting booking webb application. I want to save the content in the buttons to firebase and also the input text in the form to firebase.
I cant type text in the input field for then I get error: TypeError: Cannot read property 'refs' of undefined
enter image description here
enter image description here
import React, { Component } from "react";
import "./App.css";
import firebase from "firebase";
const uuid = require("uuid");
class App extends Component {
constructor(props) {
super(props);
this.state = {
uid: uuid.v1(),
meeting: "",
name: "",
email: ""
};
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
console.log(firebase);
var database = firebase.database();
var ref = database.ref("meeting");
var data = {
id: "",
user: ""
};
ref.push(data);
// this.state = {
// items: [],
// isLoaded: true,
// }
// this.state = {
// name: '',
// email: '',
// };
}
handleClick = e => {
console.log(e.target.innerHTML);
alert("Du har valt ett möte");
};
componentDidMount() {
fetch("http://www.mocky.io/v2/5c9cdca03300004d003f2151")
.then(res => res.json())
.then(json => {
let meetings = [];
json.forEach(meeting => {
if (
new Date(meeting.startDate).getDay() !==
new Date(meeting.endDate).getDay()
) {
let day1 = {
activity: meeting.activity,
location: meeting.location,
startDate: meeting.startDate
};
let day2 = {
activity: meeting.activity,
location: meeting.location,
endDate: meeting.endDate
};
meetings.push(day1, day2);
} else {
meetings.push(meeting);
}
});
console.log(meetings);
this.setState({
isLoaded: true,
items: meetings
});
});
firebase
.database()
.ref(`Newdata/${this.state.uid}`)
.on("value", snap => console.log("from db", snap.val()));
}
handleChange(e) {
this.setState({
name: e.target.name
});
}
handleSubmit(e) {
alert("Er bokning är bekräftad: " + this.state.value);
console.log("Du har bekräftat er bokning");
e.preventDefault();
firebase
.database()
.ref(`Newdata/${this.state.uid}`)
.set({
meeting: this.state.meeting,
name: this.state.name,
email: this.state.email
})
.catch(error => console.log(error));
}
inputData(e) {
const meeting = this.refs.meeting1.value;
const name = this.refs.name1.value;
const email = this.refs.email1.value;
this.setState({ meeting, name, email });
}
render() {
var { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<>
<div className="App">
<div className="AppHeader">
<h1>Boka ditt möte nedan</h1>
</div>
<ul>
{items.map((item, i) => (
<li key={i}>
<button
onClick={e => this.handleClick(e)}
onChange={this.inputData}
ref="meeting1"
className="select"
>
{item.activity}
<br />
Starttid: {item.startDate}
<br />
Sluttid: {item.endDate}
<br />
Plats: {item.location}
<br />
</button>
</li>
))}
</ul>
</div>
<div className="selectedMeeting">
Fyll i dina uppgifter och bekräfta
</div>
<form onSubmit={this.handleSubmit} className="bookingSection">
<label>
Name:
<input
type="text"
name={this.state.name}
onChange={this.inputData}
ref="name1"
/>
</label>
<label>
E-mail:
<input
type="text"
email={this.state.email}
onChange={this.inputData}
ref="email1"
/>
</label>
<input className="confirm" type="submit" value="Bekräfta" />
</form>
<div className="viewSelect" />
</>
);
}
}
}
export default App;
Make sure your "def" variable is defined before attempting to push it, like so:
var data = { id: "",user: "" };
var ref = [];
ref.push(...);
Either add to your constructor:
this.inputData = this.inputData.bind(this);
or use arrow syntax to preserve the lexical this:
inputData = (e) => {

Resources