Skip to content

Instantly share code, notes, and snippets.

@ozcanzaferayan
Created May 19, 2020 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozcanzaferayan/1dc9c99b1ee1088de4e009f66309f176 to your computer and use it in GitHub Desktop.
Save ozcanzaferayan/1dc9c99b1ee1088de4e009f66309f176 to your computer and use it in GitHub Desktop.
import React, { useState } from "react";
import { useRecoilState, atom, selector, useRecoilValue } from "recoil";
const todoListState = atom({
key: "todoListState",
default: [
{ name: "Apples", isCompleted: false },
{ name: "Eggs", isCompleted: false },
{ name: "Butter", isCompleted: false },
],
});
const todoListFilterState = atom({
key: "todoListFilterState",
default: "Hepsini göster",
});
const filteredTodoListState = selector({
key: "filteredTodoListState",
get: ({ get }) => {
const filter = get(todoListFilterState);
const list = get(todoListState);
switch (filter) {
case "completed":
return list.filter((item) => item.isCompleted);
case "uncompleted":
return list.filter((item) => !item.isCompleted);
default:
// all
return list;
}
},
});
function App() {
const [todoList, setTodoList] = useRecoilState(todoListState);
const [todo, setTodo] = useState({ name: "" });
const [filter, setFilter] = useRecoilState(todoListFilterState);
const filteredTodos = useRecoilValue(filteredTodoListState);
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);
};
const completeAt = (index) => {
const todos = [...todoList];
const todo = todos[index];
todos[index] = { name: todo.name, isCompleted: !todo.isCompleted };
setTodoList(todos);
};
return (
<>
<select value={filter} onChange={(e) => setFilter(e.target.value)}>
<option value="all">All</option>
<option value="completed">Completed</option>
<option value="uncompleted">Uncompleted</option>
</select>
<br />
<input
value={todo.name}
onChange={(e) => setTodo({ name: e.target.value })}
/>
<button onClick={() => setTodoList((todos) => [...todos, todo])}>
Add
</button>
{filteredTodos.map((item, index) => (
<li key={item.name}>
<span
onClick={() => completeAt(index)}
style={{
textDecoration: item.isCompleted ? "line-through" : "initial",
}}
>
{item.name}
</span>
<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