add create and delete

This commit is contained in:
davidwells 2018-06-11 18:49:12 -07:00
parent c404e856cf
commit fd5b183d00

View file

@ -16,16 +16,52 @@ class App extends Component {
.then((myJson) => {
console.log(myJson)
this.setState({
todos: myJson.data
todos: myJson
})
})
}
saveTodo = (e) => {
e.preventDefault();
if (!this.inputElement.value) {
alert('Please add todo text')
return false
}
fetch('/.netlify/functions/todos-create', {
body: JSON.stringify({
title: this.inputElement.value
}),
method: 'POST',
// mode: 'cors', // no-cors, cors, *same-origin
})
.then(response => response.json())
.then((json) => {
console.log(json)
}).catch((e) => {
console.log('errrrr', e)
})
}
deleteTodo = (e) => {
const todoId = e.target.dataset.id
console.log(`Delete todo ${todoId}`)
fetch(`/.netlify/functions/todos-delete/${todoId}`, {
method: 'POST',
})
.then(response => response.json())
.then((json) => {
console.log(json)
}).catch((e) => {
console.log('errrrr', e)
})
}
renderTodos() {
const { todos } = this.state
return todos.map((todo, i) => {
const { data } = todo
const id = todo.ref['@ref'].split('/').pop()
return (
<div key={i}>
{todo['@ref']}
<div key={i} style={{borderBottom: '1px solid black', padding: 20}}>
{data.title} <button data-id={id} onClick={this.deleteTodo}>delete</button>
</div>
)
})
@ -40,6 +76,16 @@ class App extends Component {
<p className="App-intro">
Using FaunaDB & netlify functions
</p>
<div>
<h2>Create todo</h2>
<form className='feature-add' onSubmit={this.saveTodo}>
<input placeholder='Todo Info' name='name' ref={el => this.inputElement = el} />
<button>
Create todo
</button>
</form>
</div>
{this.renderTodos()}
</div>
)