How can I do #3 is everything correct in ex.1 and ex.2
ex. 1
class todo
ex. 2
useState todo
ex. 3
please help:
Use Reducer
for those interested, I could not do it using only usereducer I still had to useState to make the state. also there is a console error that is explained by this post:
changing uncontrolled input to controlled
so probably passing an empy string to useState to be the initial state would fix it.
import React, { useReducer, useState } from "react";
function reducer(state, action) {
switch (action.type) {
case "add-todo":
return { todos: [...state.todos, { text: action.text }] };
default:
return state;
}
}
export default function App() {
const [{ todos }, dispatch] = useReducer(reducer, { todos: [] });
const [text, setText] = useState();
return (
<div>
<h1>hi</h1>
<form
onSubmit={e => {
e.preventDefault();
dispatch({ type: "add-todo", text });
setText("");
}}
>
<input value={text} onChange={e => setText(e.target.value)} />
</form>
{/* {JSON.stringify(todos)} */}
<ul>
{todos.map(x => (
<li key={x.text + Date.now() + Math.random()}>{x.text}</li>
))}
</ul>
</div>
);
}
You’re right about using an empty string as the text
state’s initial value.