I am working on some javascrit code, handling a firebase realtime database
and using React
to manage the user interface. I want to have a generic class where I can provide the name of a collection to use, as a prop.
For example, this:
<MediaInput type='movies'/>
would make a component to use the movies collection.
This:
<MediaInput type='books'/>
would make a component to use the books collection.
And so on with:
<MediaInput type='tapes'/>
or
<MediaInput type='films'/>
…etc…
Below is my current code, the problem is that it only works with the books collection.
I have tried replacing ‘books’ by ‘dbCln’ in a few ways but it did not work. Does anyone know how I need to modify the code (I assume changing the lines containing ‘books’ by lines containing ‘dbCln’ in some way) to get the result I want.
import React from 'react';
import firebase from './initFirebase';
import './MediaInput.css';
import AppDB from './AppDB.js';
class MediaInput extends React.Component {
constructor(props) {
super(props);
this.appDatabase = new AppDB();
this.state = {
books: [],
dbCln: {
[props.type]: []
}
};
}
componentDidMount() {
this.getUserData();
}
componentDidUpdate(prevProps, prevState) {
if (prevState !== this.state) {
this.writeUserData();
}
}
writeUserData = () => {
this.appDatabase.addCollection(this.state);
};
getUserData = () => {
let ref = firebase.database().ref("/");
ref.on("value", snapshot => {
const state = snapshot.val();
this.setState(state);
});
};
handleSubmit = event => {
event.preventDefault();
let name = this.refs.name.value;
let price = this.refs.price.value;
let uid = this.refs.uid.value;
if (uid && name && price) {
const { books } = this.state;
const devIndex = books.findIndex(data => {
return data.uid === uid;
});
books[devIndex].name = name;
books[devIndex].price = price;
this.setState({ books });
} else if (name && price) {
//const uid = new Date().getTime().toString();
let uid = new Date().getTime().toString();
const { books } = this.state;
books.push({ uid, name, price });
this.setState({ books });
}
this.refs.name.value = "";
this.refs.price.value = "";
this.refs.uid.value = "";
};
render() {
return (
<React.Fragment>
<div className="inp-block">
<form onSubmit={this.handleSubmit}>
<div className="form-row">
<input type="hidden" ref="uid" />
<div className="form-group col-md-6">
<label className='inp-lbl'>Name</label>
<div className='inp-name'>
<input
type="text"
ref="name"
placeholder=""
/>
</div>
</div>
<div className="form-group col-md-6">
<label className='inp-lbl'>Price</label>
<div className='inp-price'>
<input
type="text"
ref="price"
placeholder=""
/>
</div>
</div>
</div>
<div className="btn">
<button type="submit" className="btn-primary">
Save
</button>
</div>
</form>
</div>
</React.Fragment>
)
}
}
export default MediaInput;