Answer the question
In order to leave comments, you need to log in
How to use window.onload in React?
I'm learning react. I want to display the comments stored in localStorage when the page is loaded, but I can't figure out how to do it. I tried to copy the array from the state and throw everything that is in the gatehouse into it like this:
window.onload = function() {
const initialItems = [...items]
for (let i = 0; i < localStorage.length; i++) {
initialItems.push(JSON.parse(localStorage.getItem(items.itemId)));
}
setItems(items);
};
import CommentForm from './CommentForm'
import CommentList from './CommentList'
import CommentatorsTop from "./CommentatorsTop";
import {useState} from 'react';
function CommentWidget() {
const [items, setItems] = useState([]);
window.onload = function() {
const initialItems = [...items]
for (let i = 0; i < localStorage.length; i++) {
initialItems.push(JSON.parse(localStorage.getItem(items.itemId)));
}
setItems(items);
};
function addItem(item) {
const newItems = [...items]
newItems.push(item)
setItems(newItems);
const storageNewItems = JSON.stringify(newItems);
localStorage.setItem(item.itemId, storageNewItems);
}
function removeCommentItem(position, itemId) {
if (window.confirm('Удалить?')) {
const newListItem = [...items]
newListItem.splice(position, 1);
localStorage.removeItem(itemId);
setItems(newListItem);
}
}
return (
<div className="CommentWidget">
<div className="CommentForm-wrap">
<CommentForm addNewItem={addItem}/>
<CommentList comments={items} removeCommentItem={removeCommentItem} />
</div>
<CommentatorsTop names={items}/>
</div>
)
}
export default CommentWidget;
Answer the question
In order to leave comments, you need to log in
1. I found an error in the addItem function: the item element should be sent to localStorage here, and not an array, of course.
2. Definitely, you can use the powerful useEffect hook here. However, since the question was specifically about window.onload, I'll leave the solution here.
When reloading the page, copying the items array is unnecessary and pointless. You need to declare an empty array const storageItems = []
and add everything that is in localStorage to it:
for (let i = 0; i < localStorage.length; i++) {
storageItems.push(JSON.parse(localStorage.getItem(localStorage.key(i))));
}
and then pass the array to state:setItems(items);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question