Uczę się korzystac z useReducer. Napisalem w react input który po kliknieciu w przycisk dodaje element do tablicy i wyswetla na stronie, chce rowniez dodac logike która nie pozwoli dodać dwoch tych samych elementów o tej samej tresci, ale niestety to nie dziala, prosze o pomoc. Na starcie, wrzucam do tablic imiona z api : https://jsonplaceholder.typicode.com/users
const tab = []
const App = () => {
const [state, dispatch] = useReducer(
(state, action) => {
switch (action.type) {
case 'ADD':
for (const n of state) {
if (n.name === action.course.name) {
console.log('bylo to')
return
}
}
return [...state, action.course]
case 'FETCH':
return action.data
case 'REMOVE':
return state.filter(el => el.id !== action.id)
}
}, tab)
const allCourse = state.map(el => (
<CourseInfo name={el.name} key={el.id} id={el.id} removeHandle={dispatch} />
))
const fetchAsync = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/users")
const data = await response.json()
dispatch({ type: "FETCH", data })
}
useEffect(() => {
fetchAsync()
}, [])
return (
<>
<Form addCourse={dispatch} />
{ allCourse}
</>
);
}
export default App;
Form.jsx:
const Form = ({ addCourse }) => {
const [text, setText] = useState('')
const handleInput = event => {
setText(event.target.value)
}
const handleClick = () => {
const course = {
id: Math.floor(Math.random() * 1000),
name: text
}
addCourse({ type: 'ADD', course })
}
return (
<>
<input type="text" value={text} onChange={handleInput} />
<button onClick={handleClick}>Dodaj kurs</button>
</>
)
}
CourseInfo.jsx:
const CourseInfo = ({ removeHandle, name, id }) => {
const handleRemove = () => {
removeHandle({ id, type: 'REMOVE' })
}
return (
<div>
<p>{name}</p>
<button onClick={handleRemove}>Usuń</button>
</div>
)
}