Cloud Firestore + React で、CRUDの例 #firebase #noSQL #React #node #javascript


■ 概要:

Cloud Firestore 関連となり。ReactでCRUDを作るメモです
・Firestore書き込み、firebase認証は。前と同様です

■ 環境

firebase
firebase Cloud Firestore
firebase.auth.GoogleAuthProvider
React
node 10.16

■ 前の、認証等の参考

https://note.com/knaka0209/n/nbed96c774175

■ 参考のコード

■ react実装

・firebase のkey設定は。下記
 src/index.js

・Create
src/component/Task/Create.js

class Create extends Component {
   constructor(props){
       super(props)
       this.state = {title: '', content: ''}
       this.handleClick = this.handleClick.bind(this);
       this.db = null
   }
   componentDidMount(){
       this.database = firebase.firestore()
       var self = this
       firebase.auth().onAuthStateChanged(function(user) {
           if (user) {
               console.log("#Auth-OK");
           } else {
               alert("Error, auth error, please Google Login")
               self.props.history.push("/task");
               console.log('#no-User');
           }
       })        
   }
   handleChangeTitle(e){
       this.setState({title: e.target.value})
   }
   handleChangeContent(e){
       this.setState({content: e.target.value})
   }
   add_item(){
       var item = {
           title: this.state.title,
           content: this.state.content,
           created_at: new Date(),
       }
       var self = this
       if (this.newTodoName == "") { return; }        
       this.database.collection('tasks').add(item).then(function(docRef) {
           console.log("Document written with ID: ", docRef.id)
           self.props.history.push("/task");
       }).catch(function(error) {
           alert("Error save: "+ error)
           console.error("Error adding document: ", error)
       })
       this.newTodoName = ""        
   }
   handleClick(){
       console.log("#-handleClick")
       this.add_item()
//        console.log( this.state )
   }
   render() {
       return (
       <div className="container">
           <Link to="/task" className="btn btn-outline-primary mt-2">Back</Link>
           <hr className="mt-2 mb-2" />
           <h1 className="mt-2">Create - Task</h1>
           <div className="row">
           <div className="col-md-6">
               <div className="form-group">
                   <label>Title:</label>
                   <input type="text" className="form-control"
                   onChange={this.handleChangeTitle.bind(this)}/>
               </div>
           </div>
           </div>
           <div className="row">
               <div className="col-md-6">
               <div className="form-group">
                   <label>Content:</label>
                   <input type="text" className="form-control"
                    onChange={this.handleChangeContent.bind(this)}/>
               </div>
               </div>
           </div><br />
           <div className="form-group">
               <button className="btn btn-primary" onClick={this.handleClick}>Create
               </button>
           </div>
       
       </div>
       )
   }
}

・index
src/component/Task/Index.js

class Index extends Component {
   constructor(props) {
       super(props);
       this.state = {data: ''}
       this.db = null
   }
   componentDidMount(){
       this.get_items()        
   }
   get_items(){
       var items = []
       var self = this
       this.database = firebase.firestore()
       var dbRef = this.database.collection('tasks')
       dbRef = dbRef.orderBy("created_at", "desc")
       dbRef.get().then(function(querySnapshot) {
           querySnapshot.forEach(function(doc) {
               /* console.log(doc.id, " => ", doc.data()) */
               var item = doc.data()
               items.push({
                   id : doc.id,
                   title : item.title,
                   content : item.content,
                   created_at : item.created_at
               })            
           })
           self.setState({ data: items })
console.log( items )
       })        
   }
   tabRow(){
       if(this.state.data instanceof Array){
           return this.state.data.map(function(object, i){
               return <IndexRow obj={object} key={i} />
           })
       }
   }
   render(){
       return (
       <div className="container">
           <h3>Task - index</h3>
           <div className="row">
               <div className="col-md-6">
                   <Link to="/task_create"
                    className="btn btn-sm btn-primary">+ Create
                   </Link>
               </div>
               <div className="col-md-6">
               </div>
           </div><br />
           <table className="table table-hover">
               <thead>
               <tr>
                   <th>ID</th>
                   <th>Title</th>
                   <th>Conent</th>
                   <th>Actions</th>
               </tr>
               </thead>
               <tbody>
                   {this.tabRow()}
               </tbody>
           </table>
       </div>
       )
   }
}

・edit
src/component/Task/Edit.js

・Login
src/component/Users/Login.js

・Logout
src/component/Users/Logout.js

....

この記事が気に入ったらサポートをしてみませんか?