-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path10_firebase2.js
132 lines (118 loc) · 3.64 KB
/
10_firebase2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import React, { Component } from 'react';
import firebase from '../firebase';
export default class App extends Component{
state ={
todos: [],
value: ''
}
componentDidMount(){
firebase.database().ref("todos")
.orderByChild("content")
.startAt("a")
.on('child_added', (snapshot) => {
const todos = [...this.state.todos];
//Create todo
const todo = {
key: snapshot.key,
value: snapshot.val()
}
//Push todo in state
todos.push(todo);
this.setState({
todos: todos
});
})
firebase.database().ref("todos")
.on('child_removed', (snapshot) => {
//Still need the state
const todos = [...this.state.todos];
//Higher Order function
const filteredTodo = todos
.filter((item) =>{
if(item.key !== snapshot.key){
return item
}
})
this.setState({
todos: filteredTodo
});
})
firebase.database().ref("todos")
.on('child_changed', (snapshot) => {
//Copy state
const todos = [...this.state.todos];
//Loop the object
const updatedTodos = todos.map(item =>{
//If object is found
if(item.key === snapshot.key){
return Object
.assign({}, item, snapshot.val())
}else{
return item;
}
})
this.setState({
todos: updatedTodos
});
})
}
addTodo = e => {
e.preventDefault();
const todo = {
content: this.state.value,
date: (new Date()).toLocaleString()
}
firebase.database().ref("todos").push(todo);
}
removeTodo = key => {
firebase.database().ref(`todos/${key}`).remove();
}
onChange = (e) => this.setState({[e.target.name]: e.target.value})
render(){
const list = this.state.todos.map(todo =>
<div key={todo.key}>
{ todo.value.content } - {todo.value.date}
<button className="btn btn-secondary"
onClick={() => this.removeTodo(todo.key)}>
Remove me!
</button>
</div>
)
return(
<div className="container pt-5">
<div className="row justify-content-center text-center">
<form onSubmit={this.addTodo} className="col-12">
<div className="form-group">
<input
type="text"
className="form-control"
value={this.state.value}
onChange={this.onChange}
name="value"/>
</div>
<div className="form-group">
<input
type="submit"
value="Send"
className="btn btn-primary" />
</div>
</form>
</div>
<div className="row justify-content-center text-center">
<div className="col-12">
{
list
}
</div>
</div>
</div>
)
}
}
// function toArray(firebaseObject) {
// let array = []
// for(let item in firebaseObject){
// array.push({ key: item, value: firebaseObject[item] })
// }
// return array;
// }