Skip to content

Instantly share code, notes, and snippets.

@ozcanzaferayan
Created May 19, 2020 15:37
Show Gist options
  • Save ozcanzaferayan/4e652cf0e5fde0add4f6fcdc4656bfdb to your computer and use it in GitHub Desktop.
Save ozcanzaferayan/4e652cf0e5fde0add4f6fcdc4656bfdb to your computer and use it in GitHub Desktop.
import React, { useState } from "react";
import { useRecoilState, atom } from "recoil";
const todoListState = atom({
key: "todoListState",
default: [
{ name: "Apples", isCompleted: false },
{ name: "Eggs", isCompleted: false },
{ name: "Butter", isCompleted: false },
],
});
function App() {
const [todoList, setTodoList] = useRecoilState(todoListState);
const [todo, setTodo] = useState({ name: "" });
const deleteItemAt = (index) => {
const todos = [...todoList];
todos.splice(index, 1);
setTodoList(todos);
};
const editItemAt = (index) => {
const todos = [...todoList];
const todo = todoList[index];
var name = prompt("Change item name", todo.name);
todos[index] = { ...todo, name: name };
setTodoList(todos);
};
return (
<>
<input
value={todo.name}
onChange={(e) => setTodo({ name: e.target.value })}
/>
<button onClick={() => setTodoList((todos) => [...todos, todo])}>
Add
</button>
{todoList.map((item, index) => (
<li key={item.name}>
{item.name}
<button onClick={() => deleteItemAt(index)}>Delete</button>
<button onClick={() => editItemAt(index)}>Edit</button>
</li>
))}
</>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment