I am trying to save data to localStorage but I am getting error
Uncaught SyntaxError: JSON.parse: unexpected character at…
import React, { useEffect, useState } from "react";
import "./Blogs.css";
//getting values from localstorage
const getDataFromLS = () => {
const data = localStorage.getItem("blogs");
data ? JSON.parse(data) : [];
};
export const Blogs = () => {
const [blogs, setBlogs] = useState(getDataFromLS());
const [title, setTitle] = useState("");
const [author, setAuthor] = useState("");
const handleAddBlogSubmit = (e) => {
e.preventDefault();
let blog = {
title: title,
author: author,
};
setBlogs([...blogs, blog]);
setTitle("");
setAuthor("");
};
useEffect(
(blogs) => {
localStorage.setItem("blogs", JSON.stringify(blogs));
},
[blogs]
);
return (
<div className="main">
<div>
<form className="form-control" onSubmit={handleAddBlogSubmit}>
<label>Title</label>
<input
type="text"
onChange={(event) => setTitle(event.target.value)}
value={title}
/>
<label>Author</label>
<input
type="text"
onChange={(event) => setAuthor(event.target.value)}
value={author}
/>
<button type="submit">Add</button>
</form>
</div>
<div className="blogs-list">Blog List Here</div>
</div>
);
};
I checked JSON.parse documentation. I am passing string "blogs" in JSON.parse. But I may have done something wrong elsewhere as I am still learning.
2
Answers
The issue is most likely with your
getDataFromLS
function. It is not returning the parsed data from localStorage.Also why are you passing
blogs
to a callback function insideuseEffect
? Make it like thisLastly, clear your local storage, you probably have undefined assigned to
blogs