skip to Main Content

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


  1. The issue is most likely with your getDataFromLS function. It is not returning the parsed data from localStorage.

    const getDataFromLS = () => {
      const data = localStorage.getItem("blogs");
      return data ? JSON.parse(data) : [];
    };
    

    Also why are you passing blogs to a callback function inside useEffect? Make it like this

    useEffect(
        () => {
          localStorage.setItem("blogs", JSON.stringify(blogs || []));
        },
        [blogs]
      );
    

    Lastly, clear your local storage, you probably have undefined assigned to blogs

    Login or Signup to reply.
  2. import React, { useEffect, useState } from "react";
    
    //getting values from localstorage
    const getDataFromLS = () => {
      const data = localStorage.getItem("blogs");
      console.log("data==========", data);
      const a = data ? JSON.parse(data) : [];
      console.log("a=========", a);
    };
    
    export const Blogs = () => {
      const [blogs, setBlogs] = useState([]);
    
      const [title, setTitle] = useState("");
      const [author, setAuthor] = useState("");
    
      const handleAddBlogSubmit = (e) => {
        console.log("e.target");
        e.preventDefault();
        let blog = {
          title: title,
          author: author,
        };
    
        console.log("blog", blog);
        setBlogs((prevState) => {
          return [...prevState, blog];
        });
    
        console.log("blogss", blogs);
        setTitle("");
        setAuthor("");
      };
    
      useEffect(() => {
        console.log("blog");
        localStorage.setItem("blogs", JSON.stringify(blogs));
        getDataFromLS();
      }, [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>
      );
    };
    import React, { useEffect, useState } from "react";
    
    
      const [blogs, setBlogs] = useState([]);
    
      useEffect(() => {
        console.log("blog");
        localStorage.setItem("blogs", JSON.stringify(blogs));
        getDataFromLS();
      }, [blogs]);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search