I'm learning the React ropes and am attempting make my app check for local storage before making a fetch request. Pretty sure my code is solid but I keep getting this error in my console.log
VM79:1 Uncaught (in promise) SyntaxError: Unexpected token 'u', "function st"... is not valid JSON
at JSON.parse (<anonymous>)
at getPopular (Popular.jsx:19:1)
at Popular.jsx:13:1
I figure it's something to do with my if/else. Before implementing it everything is fine, but with it in (viewing from my localhost) it won't fetch and display images from the api I am using. Can anyone help?
Popular.jsx
const Popular = () => {
const [popular, setPopular] = useState([]);
useEffect(() => {
getPopular();
}, []);
const getPopular = async () => {
const check = localStorage.getItem("popular");
if (check) {
setPopular(JSON.parse(check));
} else {
const url = "https://api.spoonacular.com/recipes/random";
const apiKey = process.env.REACT_APP_API_KEY;
const res = await fetch(`${url}?apiKey=${apiKey}&number=9`);
const data = await res.json();
localStorage.setItem("popular", JSON.stringify(data.recipes));
setPopular(data.recipes);
console.log("Restore popular");
}
};
CodePudding user response:
Seems like check
is not a json. Check if it's a json before assigning to the state
const isJson = (str) => {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
const getPopular = async () => {
const check = localStorage.getItem("popular");
if (check && isJson(check)) {
setPopular(JSON.parse(check));