I have array of object as data. The data is displayed on initial page load. When Clear Book button is called with clearBooks() function, I set array to empty (No Data is displayed) and change button value to Show Books
What I am trying to achieve is when Show Books button is clicked I would like to show all objects as before. I though of refreshing page with window.location.reload(); when Show Books is clicked (If there are better solution, open to use them). I need help to achieve this functionality in code
main.js
const clearBooks = () => {
if (buttonTitle === "Clear Books") {
setButtonTitle("Show Books");
}
setBooksData([]);
};
return (
<section className="booklist">
{booksData.map((book, index) => {
return (
<Book key={index} {...book}>
</Book>
);
})}
<div>
<button type="button" onClick={clearBooks}>
{buttonTitle}
</button>
</div>
</section>
);
Data
export const books = [
{
id: 1,
img: "https://m.media/_QL65_.jpg",
author: " A ",
title: "B",
},
{
id: 2,
img: "https://m.media/_QL65_.jpg",
author: " A ",
title: "B",
},
CodePudding user response:
You could store the originally fetched data into a separate state and reset the booksData array by setting its value equal to that state on the Show Books click:
const [originalBooksData, setOriginalBooksData] = useState([]);
const [booksData, setBooksData] = useState([]);
const fetchBooks = async () => {
...
// After booksData have been fetched set originalBooksData equal to it
setOriginalBooksData(booksData)
}
const clearBooks = () => {
if (buttonTitle === 'Clear Books') {
// Clear the books
setButtonTitle('Show Books');
setBooksData([]);
} else {
// Reset the books
setBooksData(originalBooksData);
}
};
...
Of course, you will need to set the originalBooksData equal to booksData when the data are loaded.
This will prevent the need to refresh the page when clearing the data.
CodePudding user response:
You can achieve this by using useState hook.
const books = [
{
id: 1,
img: "https://m.media/_QL65_.jpg",
author: "A",
title: "B",
},
{
id: 2,
img: "https://m.media/_QL65_.jpg",
author: " A ",
title: "B",
},
]
const [bookList, setBookList] = useState(books);
const clearBooks = () => {
setBookList("");
}
const showBooks = () => {
setBookList(books);
}
Set bookList to empty when you need to clear book list and to books object when yoou want to show your list books.
