i've been using react for my project. now i'm trying to use localStorage as my main storage due to not having any database connection other than algolia.
But my localStorage code is now failed the other test (render test, etc) and getting "TypeError: Cannot read property 'getItem' of undefined" when i tried to access my localstorage in this line of code:
var collections = JSON.parse(window.localStorage.getItem('collections'));
i guess it happens because i tried to create a component but the localStorage is still undefined (or not defined yet)
here is my code to define my localStorage
import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
import Header from '../../components/header/header';
import Footer from '../../components/footer/footer';
import RecommendedCategory from '../../components/recommendedCategory/recommendedCategory';
import RecommendedItem from '../../components/recommendedItem/recommendedItem';
import './css/home.css';
class Home extends Component {
render() {
var collections, urlCollections;
if(window.localStorage.collections === undefined || window.localStorage.urlCollections === undefined){
collections = [];
urlCollections = [];
} else {
collections = JSON.parse(window.localStorage.getItem('collections'));
urlCollections = JSON.parse(window.localStorage.getItem('urlCollections'));
}
window.localStorage.setItem('collections', JSON.stringify(collections));
window.localStorage.setItem('urlCollections', JSON.stringify(urlCollections));
return (
<BrowserRouter>
<div className="Home">
<Header />
<div className="containerCategory">
<RecommendedCategory />
<RecommendedItem />
</div>
<Footer />
</div>
</BrowserRouter>
);
}
}
export default Home;
do you have any idea how to get item in localStorage without fail the render test?