I am getting this error in next js while working with localstorage it shows following error "Server Error ReferenceError: localStorage is not defined" .when i try to pass the getLocalItem() function created by me, to use in my useState([]) of setItem, in getLocalItem function i tried everything but its not working just for "localStorage inbuit function i.e getItem('')";
import { useState, useEffect } from 'react';
import Image from 'next/image';
//To get the items from local storage
const getLocalItems = () => {
let todoList = JSON.parse(localStorage.getItem('Todos'));
console.log(todoList);
if (todoList) {
return JSON.parse(localStorage.getItem('Todos'));
} else {
return [];
}
}
const Todo = () => {
const [inputData, setInputData] = useState('');
const [items, setItems] = useState(getLocalItems());
const addItem = () => {
if (inputData) {
setItems([...items, inputData]);
setInputData('');
} else {
return alert('No Data to add');
}
}
const deleteItem = (id) => {
console.log(id);
const updateditems = items.filter((ele, ind) => {
return ind !== id;
});
setItems(updateditems);
}
const removeAll = () => {
setItems([]);
}
//adding data to local storage
useEffect(() => {
localStorage.setItem('Todos', JSON.stringify(items));
}, [items])
return (
<>
<div className="main-div">
<div className='child-div'>
<figure>
<Image src='/todo.svg' alt="Picture of the author" width={150} height={150} />
<figcaption>Add Your List Here </figcaption>
</figure>
<div className='addItems'>
<input type="text" placeholder="Add Item.... " value={inputData} onChange={(e) => setInputData(e.target.value)} />
<i className="fa fa-plus add-btn" title="Add Item" onClick={addItem}></i>
</div>
<div className='showItems'>
{items.map((ele, ind) =>
<div className='eachItem' key={ind}>
<h3>{ele}</h3>
<i className="fas fa-trash-alt add-btn" title="Delete Item" onClick={() => deleteItem(ind)}></i>
</div>
)}
</div>
<div className='showItems'>
<button className='btn effect04' data-sm-link-text='Remove All' onClick={removeAll}><span>CHECK LIST</span></button>
</div>
</div>
</div>
</>
)
}
export default Todo;