import React, { useState, useEffect } from 'react';
import axios from 'axios';
const PostsResult = () => {
const [dataPosts, setDataPosts] = useState(null);
const [filter, setFilter] = useState([]);
const [checkBox, setCheckBox] = useState(false);
useEffect(() => {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => setDataPosts(response.data));
}, []);
const handleSearch = (event) => {
const searchedWord = event.target.value;
const filteredWord = [...dataPosts].filter((value) => {
return value.title.toLowerCase().includes(searchedWord.toLowerCase());
});
setFilter(filteredWord);
};
console.log('checkBox', checkBox);
useEffect(() => {
if (checkBox) {
const filterChecked = [...filter].filter((v) => v.userId === 10);
setFilter(filterChecked);
console.log('filter 10', filterChecked);
} else {
setFilter((prevState) => {
return prevState;
});
console.log('filter', filter);
}
}, [checkBox]);
const handleChange = (event) => {
// setCheckBox(!checkBox);
// const checked = event.currentTarget.value;
// if (checkBox) {
// // const filterChecked = [...filter].filter(
// // (test) => (test.userId = checked)
// // );
// // return filterChecked;
// return setFilter(filterChecked);
// }
console.log(checked);
};
return (
<>
<input
type="text"
placeholder="Search for article..."
className="inputText"
onChange={handleSearch}
/>
<label htmlFor="checkBoxId" className="checkBoxLabel">
User Id 10
<input
id="checkBoxId"
type="checkbox"
className="checkbox"
onChange={() => setCheckBox(!checkBox)}
// checked={() => setCheckBox(!checkBox)}
value="10"
/>
</label>
<div className="container">
{filter != null &&
filter.map((dataPost) => {
return (
<div key={dataPost.id} className="singlePost">
<div>{dataPost.userId}</div>
<div>{dataPost.title}</div>
<div>{dataPost.body}</div>
</div>
);
})}
</div>
</>
);
};
export default PostsResult;
как вернуть к первоначальному состоянию когда unchecked не понимаю
function Posts() {
const [ posts, setPosts ] = useState([]);
const [ filteredPosts, setFilteredPosts ] = useState([]);
const [ search, setSearch ] = useState('');
const [ checkbox, setCheckbox ] = useState(false);
useEffect(() => {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then(r => setPosts(r.data));
}, []);
useEffect(() => {
let filtered = posts;
if (search) {
const s = search.toLowerCase();
filtered = filtered.filter(n => n.title.toLowerCase().includes(s));
}
if (checkbox) {
filtered = filtered.filter(n => n.userId === 10);
}
setFilteredPosts(filtered);
}, [ posts, search, checkbox ]);
return (
<>
<input
type="text"
placeholder="Search for article..."
value={search}
onChange={e => setSearch(e.target.value)}
/>
<label>
User Id 10
<input
type="checkbox"
checked={checkbox}
onChange={e => setCheckbox(e.target.checked)}
/>
</label>
<ul>
{filteredPosts.map(n => (
<li key={n.id}>
<div>{n.userId}</div>
<div>{n.title}</div>
<div>{n.body}</div>
</li>
))}
</ul>
</>
);
}