Skip to content

Instantly share code, notes, and snippets.

@shuantsu-zz
Last active April 26, 2021 17:11
Show Gist options
  • Save shuantsu-zz/1ebf4c9f91112db99c0bc8eb5ee8ba5d to your computer and use it in GitHub Desktop.
Save shuantsu-zz/1ebf4c9f91112db99c0bc8eb5ee8ba5d to your computer and use it in GitHub Desktop.
react todo
import ReactDOM from 'react-dom';
import { React, useEffect, useState } from "react";
import './style.css';
function App() {
const [ value, setValue ] = useState("");
const [ tasks, setTasks ] = useState([]);
const [ ask, setAsk ] = useState(false);
useEffect(()=>{
// carregar dados
const t = localStorage.getItem("tasks");
if (t) setTasks(JSON.parse(t));
const a = localStorage.getItem("ask");
if (a) setAsk(JSON.parse(a));
const v = localStorage.getItem("value");
if (v) setValue(JSON.parse(v));
}, []);
useEffect(()=>{
// salvar tarefa atual
localStorage.setItem('value', JSON.stringify(value));
}, [value]);
useEffect(()=>{
// salvar checkbox
localStorage.setItem('ask', JSON.stringify(ask));
}, [ask]);
useEffect(()=>{
// salvar tasks
localStorage.setItem("tasks", JSON.stringify(tasks));
}, [tasks]);
const submit = () => {
// nova task
setTasks([...tasks, value]);
setValue("");
};
const enter = (ev) => {
// enter handler
if (ev.key === "Enter" && value.trim().length !== 0) {
submit();
}
}
const remove = (n) => {
// remover
if (ask) {
if (!window.confirm('Remover realmente?')) {
return false;
}
}
const tasksClone = [...tasks];
tasksClone.splice(n, 1);
setTasks(tasksClone);
};
return<>
<label><input checked={ask} onChange={()=>setAsk(!ask)} type="checkbox" /> Perguntar antes de deletar</label>
<br/><br/>
<input onKeyDown={(ev)=>enter(ev)} placeholder="Tarefa" value={value} onChange={(ev) => setValue(ev.target.value)} type="text" />
<button disabled={value.trim().length===0} onClick={submit}>Enviar</button>
<br/><br/>
<ul>
{tasks.map( (task, n) =><li onClick={()=>remove(n)} className="task" key={n}>{task}</li>)}
</ul>
</>;
}
ReactDOM.render(<App />, document.getElementById('root'));
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
padding: 20px;
min-height: 100vh;
background: linear-gradient(45deg, rgb(65, 137, 219), rgb(102, 0, 219));
font-family: sans-serif;
color: white;
}
.task {
cursor: pointer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment