2020年04月16日

Firebase☓ReactでTODOリスト作成(Update)

Firebase☓ReactでTODOリスト作成(Sort)の続き

POSTで追加だったのでPUTの場合に更新されるように変更

exports.post= functions.https.onRequest(async (request, response) => {
return cors()(request, response, () => {
if(request.method === "POST"){
const todo = {
'title': request.body.title,
'comment': request.body.comment,
'checked': false,
'createdAt': new Date()
};
const newTodo = db.collection("todos").doc()
newTodo.set(todo)
response.send("ok1");
}
if(request.method === "PUT"){
const todo = {
'title': request.body.title,
'comment': request.body.comment,
'checked': false,
};
const newTodo = db.collection("todos").doc(request.body.id)
newTodo.update(todo)
response.send("ok2");
}
})
});


React部分は以下のようになってる。擬似的に編集ページをつくったので長め

function App() {
const [mode,changeMode] = useState("list");
const [editId,changeEditId] = useState(null);
const [todos,changeTodos] = useState([]);
const [title,changeTitle] = useState("");
const [comment,changeComment] = useState("");
useEffect(()=>{
fetchResponse()
},[])

const fetchResponse = async () => {
const res = await axios.get(PATH + 'list')
changeTodos(res.data);
}

// 新規追加
const addTodo = async () => {

await axios.post(PATH + 'post',{
title,
comment,
checked:false
})
fetchResponse()
changeTodos([])
changeTitle("")
changeComment("")
}

const editTodo = async () => {
await axios.put(PATH + 'post',{
id:editId,
title,
comment,
checked:false
})
fetchResponse()
changeTodos([])
changeTitle("")
changeComment("")
changeMode("list")
}

const changeEditMode = (id) =>{
changeMode("edit")
changeEditId(id)
const todo = todos.find(todo => todo.id===id)
changeTitle(todo.title)
changeComment(todo.comment)
}

return (
<div className="App">
{mode === 'list' && (
<div>
title:<input type="text" value={title} onChange={e => changeTitle(e.currentTarget.value)} /><br />
comment:<input type="text" value={comment} onChange={e => changeComment(e.currentTarget.value)} /><br />
<button onClick={() => addTodo()}>add</button><br />
<ul>
{todos && todos.map((todo)=>(
<li key={todo.id}>
<input type="button" value="edit" onClick={()=> changeEditMode(todo.id)}/ >
{todo.title}
</li>
))}
</ul>
</div>
)}
{mode === 'edit' && (
<div>
title:<input type="text" value={title} onChange={e => changeTitle(e.currentTarget.value)} /><br />
comment:<input type="text" value={comment} onChange={e => changeComment(e.currentTarget.value)} /><br />
<button onClick={() => editTodo()}>edit</button><br />
</div>
)}
</div>
);
}
posted by ねこまんま at 22:40 | Firebase | 更新情報をチェックする