Updates nested value in React State - javascript

I am using React/Redux for my web-app and I have the Description Class where user can edit description. Props description and propertyTypes are coming from AJAX calls.
import React, { PropTypes } from 'react';
const defaultDescription = {
about_you: '',
benefits: '',
description: '',
headline: '',
no_of_guests: 0,
property_name: '',
property_type: {
id: 1,
name: 'Apartment',
},
};
class Description extends React.Component {
static propTypes = {
description: PropTypes.object,
propertyTypes: PropTypes.array,
};
constructor(props) {
super(props);
this.state = {
description: defaultDescription,
};
this.handleInputChange = this.handleInputChange.bind(this);
this.propertyTypeChanged = this.propertyTypeChanged.bind(this);
this.updateDescription = this.updateDescription.bind(this);
}
// componentWillMount() {
// if (!this.props.description) {
// this.setState({
// description: defaultDescription,
// });
// }
// }
componentWillReceiveProps(nextProps) {
if (nextProps && nextProps.description && nextProps.propertyTypes) {
const newDescription = nextProps.description.description ? merge(defaultDescription, nextProps.description) : merge(nextProps.description, defaultDescription);
this.setState({
description: newDescription,
});
}
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
description[name]: value // <---- I want to update my state here
});
}
updateDescription(event) {
event.preventDefault();
console.log(this.state);
}
render() {
return (
<form name="descriptionForm" onSubmit={this.updateDescription}>
<input name="no_of_guests" value={this.state.description.no_of_guests} onChange={this.handleInputChange} /><br />
<input name="property_name" value={this.state.description.property_name} floatingLabelText="Property Name" onChange={this.handleInputChange} /><br />
<input name="headline" value={this.state.description.headline} floatingLabelText="Headline" onChange={this.handleInputChange} /><br />
<input name="summary" value={this.state.description.summary} floatingLabelText="Summary" onChange={this.handleInputChange} /><br />
<input name="description" value={this.state.description.description} floatingLabelText="Description" onChange={this.handleInputChange} /><br />
<input name="about_you" value={this.state.description.about_you} floatingLabelText="About You" onChange={this.handleInputChange} /><br />
<input name="why" value={this.state.description.why} floatingLabelText="Why ?" onChange={this.handleInputChange} /><br />
<input name="benefits" value={this.state.description.benefits} floatingLabelText="Benefits" onChange={this.handleInputChange} /><br />
<button value="Save" type="submit" />
</form>
);
}
}
export default Description;
I want to update the form but whenever the onChange event is fired , I can not update the state, and Input field is not changed.
How do I handle this case.
Any help would be appreciated.
Thanks.

You could write the update like this:
const desc = Object.assign({}, this.state.description);
desc[name] = value;
this.setState({
description: desc
});

This is how I would update in your case
const newState = {...this.state.description};
newState[name] = value;
this.setState({
description: newState,
});
Input elements should not switch from controlled to uncontrolled (or vice versa) [[https://facebook.github.io/react/docs/forms.html#controlled-components]]

Related

In React, state is not being updated properly when concatenating individual input state values

I have seven different input fields and updating the state with the entered value. After that, I am concatenating all the state values and updating the contractNum state but it is not being updated correctly. It is missing the first state (this.state.contact.sys) value. I am not sure how to get the right concatenated value. Any help is much appreciated.
export default class test extends Component {
state = {
contact: {
sys: '',
co: '',
lgr: '',
mgr: '',
sub: '',
serial: '',
num: ''
},
contractNum: ''
};
test = testValue => {
this.setState({
contractNum: testValue
});
};
handleChangeFor = propertyName => event => {
const { contact } = this.state;
const newContact = {
...contact,
[propertyName]: event.target.value
};
this.setState({ contact: newContact });
let newValue =
contact.sub +
contact.co +
contact.mgr +
contact.lgr +
contact.sub +
contact.serial +
contact.num;
this.test(newValue);
};
render() {
return (
<div className="wrapper">
<div className="container">
<form>
<input
type="text"
onChange={this.handleChangeFor('sys')}
value={this.state.contact.sys}
maxLength={2}
/>
<input
type="text"
onChange={this.handleChangeFor('co')}
value={this.state.contact.co}
maxLength={1}
/>
<input
type="text"
onChange={this.handleChangeFor('mgr')}
value={this.state.contact.mgr}
maxLength={1}
/>
<input
type="text"
onChange={this.handleChangeFor('lgr')}
value={this.state.contact.lgr}
maxLength={1}
/>
<input
type="text"
onChange={this.handleChangeFor('serial')}
value={this.state.contact.serial}
maxLength={6}
/>
<input
type="text"
onChange={this.handleChangeFor('num')}
value={this.state.contact.num}
maxLength={2}
/>
<input
type="text"
onChange={this.handleChangeFor('sub')}
value={this.state.contact.sub}
maxLength={1}
/>
</form>
</div>
</div>
);
}
}
You used contact.sub instead of contact.sys when setting newValue.

React. Transferring data from textarea to array JSON

I just started working with React and JSON and require some help. There is a textarea field in which a user enters some data. How to read row-wise the entered text as an array into a JSON variable of the request? Any assistance would be greatly appreciated.
The result I want is
{
id: 3,
name: 'Monika',
birthDay: '1999/01/01',
countryDTO: 'USA',
films: [
'Leon:The Professional',
'Star wars',
'Django Unchained',
],
} ```
My code:
import React from 'react';
import { Form, FormGroup, Label } from 'reactstrap';
import '../app.css';
export class EditActor extends React.Component {
state = {
id: '',
name: '',
birthDay: '',
countryDTO: '',
films: [],
}
componentDidMount() {
if (this.props.actor) {
const { name, birthDay, countryDTO, films } = this.props.actor
this.setState({ name, birthDay, countryDTO, films });
}
}
submitNew = e => {
alert("Actor added"),
e.preventDefault();
fetch('api/Actors', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.state.name,
birthDay: this.state.birthDay,
countryDTO: {
title: this.state.countryDTO
},
films: [{ title: this.state.films }]
})
})
.then(() => {
this.props.toggle();
})
.catch(err => console.log(err));
this.setState({
id: '',
name: '',
birthDay: '',
countryDTO: '',
films: ''
});
}
onChange = e => {
this.setState({ [e.target.name]: e.target.value })
}
render() {
return <div>
<table>
<tr>
<td colspan="2">
<h3> <b>Add actor</b></h3>
<FormGroup>
<Label for="id">Id: </Label>
<input type="text" name="id" onChange={this.onChange} value={this.state.id} /><p />
<Label for="name">Name:</Label>
<input type="text" name="name" onChange={this.onChange} value={this.state.name} /><p />
<Label for="birthDay">Birth day:</Label>
<input type="text" name="birthDay" onChange={this.onChange} value={this.state.birthDay} placeholder="1990/12/31" /><p />
<Label for="country">Country:</Label>
<input type="text" name="countryDTO" onChange={this.onChange} value={this.state.countryDTO} /><p />
<Label for="Films">Films:</Label>
<textarea name="films" value={this.state.films} onChange={this.onChange} /><p />
</FormGroup>
</td>
</tr>
<tr>
<td>
<Form onSubmit={this.submitNew}>
<button class="editButtn">Enter</button>
</Form>
</td>
</tr>
</table >
</div>;
}
}
export default EditActor;
If you change the below code it will work automatically.
State declaration
this.state = {
name: 'React',
films:["Palash","Kanti"]
};
Change in onechange function
onChange = e => {
console.log("values: ", e.target.value)
this.setState({ [e.target.name]: e.target.value.split(",") })
}
change in textarea
<textarea name="films" value={this.state.films.map(r=>r).join(",")} onChange={this.onChange} />
Code is here:
https://stackblitz.com/edit/react-3hrkme
You have to close textarea tag and the following code is :
<textarea name="films" value={this.state.films} onChange={this.onChange} >{this.state.films}</textarea>
My understanding of your problem is that you would like to have each line in the text area dynamically added as an entry in the films array. This can be achieved as follows:
import React, { Component } from "react";
export default class textAreaRowsInState extends Component {
constructor(props) {
super(props);
this.state = {
currentTextareaValue: "",
films: []
};
}
handleChange = e => {
const { films } = this.state;
const text = e.target.value;
if (e.key === "Enter") {
// Get last line of textarea and push into films array
const lastEl = text.split("\n").slice(-1)[0];
films.push(lastEl);
this.setState({ films });
} else {
this.setState({ currentTextareaValue: text });
}
};
render() {
const { currentTextareaValue } = this.state;
return (
<textarea
defaultValue={currentTextareaValue}
onKeyPress={this.handleChange}
/>
);
}
}
Keep in mind that this method is not perfect. For example, it will fail if you add a new line anywhere other than at the end of the textarea. You can view this solution in action here:
https://codesandbox.io/s/infallible-cdn-135du?fontsize=14&hidenavigation=1&theme=dark
change textarea() tag
to
<textarea name="films" value={this.state.films} onChange={this.onChange} >{this.state.films}</textarea>
You can use split() :
films: {this.state.films.split(",")}

How to save input entered by the user in a state which is an array in React

The whole idea is to take users input in a form and display their input in a JSON object. In state I have an array and inside it another array.
My Form.js looks like this,
state= {
groups:[{
typeA:[{}],
typeB:[{}]
}],
credentials: false
};
change = e =>{
this.setState({[e.target.name]: e.target.value})
};
handleSubmit(event) {
event.preventDefault();
this.setState({
credentials: true
});
}
render(){
return(
<div class="classform">
<form >
<label>
Field1:
<br/>
<input type="text"
name="typeA"
placeholder="Type A"
//store it as the first element of the type A
value={this.state.groups.typeA[0]}
onChange={this.change.bind(this)}
/>
//other fields with the same code
Subsequently, Field2 will be stored as the second element of type A
Then, Field3 and Field4 will be stored as 2 of type B array
I expect the code to give me an output like :
"typeA": ["field1 value", "field2 value"],
"typeB": ["field3 value", "field4 value"]}
I'm a beginner with React and I'm not able to store the field values in the state which is an array.
For the sake of simplicity, I will recommend below solution,
Instead of having a nested array in the state, you can manage the input values in the different state variables and at the time of submitting, change them to the output you want.
state = {
field1: '',
field2: '',
field3: '',
field4: '',
}
change = e => {
this.setState({[e.target.name]: e.target.value})
};
handleSubmit(event) {
event.preventDefault();
const { field1, field2, field3, field4 } = this.state;
// This is your output
const output = [{typeA: [field1, field2], typeB: [field2, field3]}];
this.setState({
credentials: true
});
}
render(){
return(
<div class="classform">
<form >
<label>
Field1:
<br/>
<input type="text"
name="field1"
placeholder="Type A"
value={this.state.field1}
onChange={this.change}
/>
</label>
<label>
Field2:
<br/>
<input type="text"
name="field2"
placeholder="Type A"
value={this.state.field2}
onChange={this.change}
/>
</label>
try this:
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
groups: [
{
typeA: [{}],
typeB: [{}]
}
],
credentials: false
};
}
change = (e, key) => {
let { groups } = this.state;
let myVal = groups[0][e.target.name];
// or if you want to add value in an object likr [{value: 'abcd'}]
myVal[0][key] = e.target.value;
groups[0][e.target.name] = myVal;
console.log("TCL: App -> groups", groups);
this.setState({ groups });
};
render() {
return (
<div>
<input
type="text"
name="typeA"
placeholder="Type A"
value={this.state.groups[0].typeA[0].value2}
onChange={e => this.change(e, "value2")}
/>
<input
type="text"
name="typeA"
placeholder="Type A2"
value={this.state.groups[0].typeA[0].value}
onChange={e => this.change(e, "value")}
/>
<br />
<input
type="text"
name="typeB"
placeholder="Type b"
value={this.state.groups[0].typeB[0].value}
onChange={e => this.change(e, "value")}
/>
</div>
);
}
}
Give each input a custom attribute, for example data-group="typeA". In your on change function get that value and add the values to the correct array.
<input
type="text"
name="col2"
placeholder="Type A"
data-group="typeA" // add custom attribute typeA | typeB etc.
onChange={e => this.change(e)}
/>
In your change handle get the custom attribute, and use it to add the value to the correct array.
change = e => {
// create a copy of this.state.groups
const copyGroups = JSON.parse(JSON.stringify(this.state.groups));
// get data-group value
const group = event.target.dataset.group;
if (!copyGroups[0][group]) {
copyGroups[0][group] = []; // add type if it doesn't exists
}
const groups = copyGroups[0][group];
const index = this.findFieldIndex(groups, e.target.name);
if (index < 0) {
// if input doesn't exists add to the array
copyGroups[0][group] = [...groups, { [e.target.name]: e.target.value }];
} else {
// else update the value
copyGroups[0][group][index][e.target.name] = e.target.value;
}
this.setState({ groups: copyGroups });
};
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
function formatState(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (match) => match);
}
const Credentials = ({ value }) => {
return <pre>{formatState(value)}</pre>;
};
class App extends React.Component {
state = {
groups: [
{
typeA: [],
typeB: []
}
],
credentials: false
};
handleSubmit = event => {
event.preventDefault();
this.setState({
credentials: true // display Credentials component
});
};
// get the current input index in the array typeA | typeB
findFieldIndex = (array, name) => {
return array.findIndex(item => item[name] !== undefined);
};
change = e => {
// create a copy of this.state.groups
const copyGroups = JSON.parse(JSON.stringify(this.state.groups));
// get data-group value
const group = event.target.dataset.group;
if (!copyGroups[0][group]) {
copyGroups[0][group] = []; // add new type
}
const groups = copyGroups[0][group];
const index = this.findFieldIndex(groups, e.target.name);
if (index < 0) {
// if input doesn't exists add to the array
copyGroups[0][group] = [...groups, { [e.target.name]: e.target.value }];
} else {
// update the value
copyGroups[0][group][index][e.target.name] = e.target.value;
}
this.setState({ groups: copyGroups });
};
removeKey = (key) => {
const temp = {...this.state};
delete temp[key];
return temp;
}
render() {
return (
<div>
<input
type="text"
name="col1"
placeholder="Type A"
data-group="typeA"
onChange={e => this.change(e)}
/>
<input
type="text"
name="col2"
placeholder="Type A"
data-group="typeA"
onChange={e => this.change(e)}
/>
<input
type="text"
name="col2"
placeholder="Type B"
data-group="typeB"
onChange={e => this.change(e)}
/>
<input
type="text"
name="typec"
placeholder="Type C | New Type"
data-group="typeC"
onChange={e => this.change(e)}
/>
<input
type="text"
name="typed"
placeholder="Type D | New Type"
data-group="typeD"
onChange={e => this.change(e)}
/>
<button onClick={this.handleSubmit}>Submit</button>
{this.state.credentials && (
<Credentials value={JSON.stringify(this.removeKey('credentials'), undefined, 2)} />
)}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
</script>

Performing state and array manipulation more than once by passing props only once

I am new to React and this thing is confusing me a lot. I have root component that has an array and I am passing functions ADD and DELETE as props to the child component ui_forms. In the child component, I am taking input parameters and pushing or deleting from array depending on the button pressed. However, I cannot seem to perform push/delete operation more than once because I guess I am injecting the child component only once in the root component.
Is there by any chance a way to perform push or delete as many times a user wants by sending props only once?
Thank you
App.js
import FormsMap from './form_map';
class App extends Component {
state = {
maps : [
{'regno' : 'Karan', 'id' : 1},
{regno : 'Sahil', 'id' : 2},
{'regno' : 'Rahul', id : 4},
{regno : 'Mohit', id : 5},
{regno : 'Kartik', id : 3}
]
};
function_as_props(list1) {
console.log(this.state.maps);
let ninja = [...this.state.maps];
console.log(ninja);
ninja.push({"regno" : list1, "id" : Math.random()*10});
this.setState({
maps : ninja
});
console.log(ninja);
function_as_props1(name) {
let t = this.state.maps.indexOf(name);
let x = this.state.maps.splice(t,1);
console.log(x);
this.setState({
maps : x
});
console.log(this.state.maps);
}
}
render() {
const p = this.state.maps.map(list => {
return(
<div key={list.id}> {list.regno} </div>
);
})
return(
<FormsMap transpose = {this.function_as_props.bind(this)} traverse ={this.function_as_props1.bind(this)} /> <br />
);
}
}
export default app;
form_map.js
import React, { Component } from 'react';
class FormsMap extends Component {
state = {
name : null,
age : null,
hobby : null
};
changes(e) {
this.setState({
[e.target.id] : e.target.value
});
}
handle = (e) => {
e.preventDefault();
console.log(this.state);
this.props.transpose(this.state.name);
}
dels = (e) => {
this.setState({
[e.target.id] : e.target.value
});
}
del_button(e) {
e.preventDefault();
//console.log(this.state.name);
this.props.traverse(this.state.name);
}
render() {
return(
<React.Fragment>
<form onSubmit={this.handle}> {/* After entering all info, Press Enter*/}
<label htmlFor="labels"> Name : </label>
<input type="text" id="name" placeholder="Your name goes here..." onChange={this.changes.bind(this)} />
<label htmlFor="labels"> Age : </label>
<input type="text" id="age" placeholder="Your age goes here..." onChange={this.changes.bind(this)} />
<label htmlFor="labels"> Hobby : </label>
<input type="text" id="hobby" placeholder="Your hobby goes here..." onChange={this.changes.bind(this)} /> <br /><br />
<input type="submit" value="SUBMIT" /><br /><br />
</form>
<input type="text" id="name" placeholder="Enter name to delete..." onChange={this.dels} /> <button onClick={this.del_button.bind(this)}> DELETE </button>
</React.Fragment>
);
}
}
export default FormsMap;
Try this
App.js
import React, { Component } from "react";
import FormsMap from "./components/FormsMap";
class App extends Component {
constructor(props) {
super(props);
this.state = {
maps: [
{ regno: "Karan", id: 1 },
{ regno: "Sahil", id: 2 },
{ regno: "Rahul", id: 4 },
{ regno: "Mohit", id: 5 },
{ regno: "Kartik", id: 3 }
]
};
}
function_as_props(list1) {
let ninja = this.state.maps.concat({
regno: list1,
id: Math.random() * 10
});
this.setState({ maps: ninja });
}
function_as_props1(name) {
let x = this.state.maps.filter(
list => list.regno.toLocaleLowerCase() !== name.toLocaleLowerCase()
);
this.setState({
maps: x
});
}
render() {
return (
<React.Fragment>
{this.state.maps.map(list => <div key={list.id}>{list.regno}</div>)}
<FormsMap
transpose={this.function_as_props.bind(this)}
traverse={this.function_as_props1.bind(this)}
/>
</React.Fragment>
);
}
}
export default App;
FormsMap.js
import React, { Component } from "react";
class FormsMap extends Component {
state = {
name: null,
age: null,
hobby: null
};
changes(e) {
this.setState({
[e.target.id]: e.target.value
});
}
handle = e => {
e.preventDefault();
this.props.transpose(this.state.name);
};
dels = e => {
this.setState({
[e.target.id]: e.target.value
});
};
del_button(e) {
e.preventDefault();
this.props.traverse(this.state.name);
}
render() {
return (
<React.Fragment>
<form onSubmit={this.handle}>
{" "}
{/* After entering all info, Press Enter*/}
<label htmlFor="labels"> Name : </label>
<input
type="text"
id="name"
placeholder="Your name goes here..."
onChange={this.changes.bind(this)}
/>
<label htmlFor="labels"> Age : </label>
<input
type="text"
id="age"
placeholder="Your age goes here..."
onChange={this.changes.bind(this)}
/>
<label htmlFor="labels"> Hobby : </label>
<input
type="text"
id="hobby"
placeholder="Your hobby goes here..."
onChange={this.changes.bind(this)}
/>{" "}
<br />
<br />
<input type="submit" value="SUBMIT" />
<br />
<br />
</form>
<input
type="text"
id="name"
placeholder="Enter name to delete..."
onChange={this.dels}
/>{" "}
<button onClick={this.del_button.bind(this)}> DELETE </button>
</React.Fragment>
);
}
}
export default FormsMap;
This is the demo: https://codesandbox.io/s/xl97xm6zpo

Reactjs to firebase db: Trouble adding multiple children to firebase db

So I was following a simple react/firebase chat room on youtube: https://www.youtube.com/watch?v=or3Gp29o6fE as a reference to what I'm doing with my project. I am making a bug/issue tracker, so that a user can enter a station #, bug/issue, then a description of it. I keep getting an error:
Error: Reference.set failed: First argument contains undefined in property 'bugs.0.station'
And I'm not sure how it's undefined if it's just an id number. My end goal at this point in time is to be able to add and remove a bug/issue by id.
import React, { Component } from 'react';
import { Button } from "react-bootstrap";
import withAuthorization from './withAuthorization';
import * as firebase from 'firebase';
class HomePage extends Component {
constructor(props,context) {
super(props,context);
this.stationBug = this.stationBug.bind(this)
this.issueBug = this.issueBug.bind(this)
this.descBug = this.descBug.bind(this)
this.submitBug = this.submitBug.bind(this)
this.state = {
station: '',
bug: '',
desc: '',
bugs: []
}
}
componentDidMount() {
firebase.database().ref('bugs/').on ('value', (snapshot) => {
const currentBugs = snapshot.val()
if (currentBugs != null) {
this.setState({
bugs: currentBugs
})
}
})
}
stationBug(event) {
this.setState({
station: event.target.value
});
}
issueBug(event) {
this.setState({
bug: event.target.value
});
}
descBug(event) {
this.setState({
desc: event.target.value
});
}
submitBug(event) {
const nextBug = {
id: this.state.bugs.length,
station: this.state.title,
bug: this.state.bug,
desc: this.state.desc
}
firebase.database().ref('bugs/'+nextBug.id).set(nextBug)
}
render() {
return (
<div className="App">
{
this.state.bugs.map((bug, i) => {
return (
<li key={bug.id}>{bug.station}</li>
)
})
}
<input onChange={this.stationBug} type="text" placeholder="Station #" />
<br />
<textarea onChange={this.issueBug} type="text" placeholder="Bug/Issue" />
<br />
<textarea onChange={this.descBug} type="text" placeholder="Bug Description" />
<br />
<Button onClick={this.submitBug} type="button"> Enter Bug </Button>
</div>
);
}
}
export default withAuthorization()(HomePage);
Just looks like a typo. You're referencing this.state.title instead of this.state.station in your submitBug method.
class HomePage extends Component {
constructor(props) {
super(props);
this.state = {
station: '',
bug: '',
desc: '',
bugs: []
}
}
componentDidMount() {
firebase.database().ref('bugs/').on ('value', (snapshot) => {
const currentBugs = snapshot.val()
if (currentBugs != null) {
this.setState({
bugs: currentBugs
})
}
})
}
stationBug=(event)=>{
this.setState({
station: event.target.value
});
}
issueBug=(event)=>{
this.setState({
bug: event.target.value
});
}
descBug=(event)=>{
this.setState({
desc: event.target.value
});
}
submitBug=(event)=>{
const nextBug = {
id: this.state.bugs.length,
station: this.state.title,
bug: this.state.bug,
desc: this.state.desc
}
firebase.database().ref('bugs/'+nextBug.id).set(nextBug)
}
render() {
return (
<div className="App">
{this.state.bugs.map(bug => <li key={bug.id}>{bug.station}</li>)}
<input onChange={this.stationBug} type="text" placeholder="Station #" />
<br />
<textarea onChange={this.issueBug} type="text" placeholder="Bug/Issue" />
<br />
<textarea onChange={this.descBug} type="text" placeholder="Bug Description" />
<br />
<Button onClick={this.submitBug} type="button"> Enter Bug </Button>
</div>
);
}
}
export default withAuthorization()(HomePage);
The error is quite explicit:
Reference.set failed: First argument contains undefined in property 'bugs.0.station'
Since there's only one call to Reference.set() in your code, the problem must be here:
submitBug(event) {
const nextBug = {
id: this.state.bugs.length,
station: this.state.title,
bug: this.state.bug,
desc: this.state.desc
}
firebase.database().ref('bugs/'+nextBug.id).set(nextBug)
}
So it seems that this.state.title is undefined. Most likely you wanted to use station: this.state.station.

Categories