When I set a variable through useState, first of all, data is loaded from local storage. On the local server everything works fine, but on Github Pages everything breaks and it returns the variable favoriteCats as Null. What could be the reason? I tried changing localStorage to sessionStorage, didn't help.
import {useEffect, useState} from "react";
import {Route, Routes} from "react-router-dom";
import axios from 'axios'
import './App.css';
import Header from "../Header/Header";
import CatsList from "../CatsList/CatsList";
import FavoriteCats from "../CatsList/FavoriteCats";
function App() {
const [catsList, setCatsList] = useState([]);
const [favoriteCats, setFavoriteCats] = useState(() => {
const cats = JSON.parse(localstorage.getItem("favoriteCats"));
if (cats !== null) {
return cats
} else return []
});
const [currentPage, setCurrentPage] = useState(1);
const [fetching, setFetching] = useState(true);
useEffect(() => {
document.addEventListener('scroll', scrollHandler)
return function () {
document.removeEventListener('scroll', scrollHandler)
}
}, [])
useEffect(() => {
if (fetching) {
axios.get(`https://api.thecatapi.com/v1/images/search?format=json&limit=15&_page=${currentPage}`,
{headers: {"x-api-key": "03b1c2d3-fb3d-4363-9e71-949a93d8d9f8"}})
.then(res => {
setCatsList(catsList => [...catsList, ...res.data])
setCurrentPage(prevState => prevState 1)
})
.finally(() => setFetching(false))
}
}, [fetching])
const scrollHandler = (e) => {
if (e.target.documentElement.scrollHeight - (e.target.documentElement.scrollTop window.innerHeight) < 100) {
setFetching(true)
}
}
useEffect(() => {
setFavoriteCats(JSON.parse(localstorage.getItem('favoriteCats')))
}, []);
useEffect(() => {
localstorage.setItem('favoriteCats', JSON.stringify(favoriteCats));
},[favoriteCats])
return (
<div className="App">
<Header />
<Routes>
<Route exact path='/' element={<CatsList list={catsList} setFavoriteCats={setFavoriteCats} favoriteCats={favoriteCats}/>} />
<Route path={'/favorite'} element={<FavoriteCats favoriteCats={favoriteCats} setFavoriteCats={setFavoriteCats}/>} />
</Routes>
</div>
);
}
export default App;
Error logs. enter image description here
Link on my Github repository: https://github.com/sanny410/frontend-challenge Link on Deploy: https://sanny410.github.io/frontend-challenge/
CodePudding user response:
The below code caused the state to be set to null
useEffect(() => {
setFavoriteCats(JSON.parse(localstorage.getItem('favoriteCats')))
}, []);
Removing it fixed the problem as the valid parsing is already done here:
const [favoriteCats, setFavoriteCats] = useState(() => {
const cats = JSON.parse(localstorage.getItem("favoriteCats"));
if (cats !== null) {
return cats
} else return []
});
CodePudding user response:
Try this:
const [favoriteCats, setFavoriteCats] = useState(JSON.parse(localStorage.getItem('favoriteCats')) || [])