Home > database >  Parsing error: Expression or comma expected while calling localStorage
Parsing error: Expression or comma expected while calling localStorage

Time:01-31

I have this query:

export const getPosts = async () => {
    try {
        const posts = await JSON.parse(localStorage?.getItem('Posts') || "{}")
        return posts
    } catch (error) {
        return error
    }
}

And i'm calling it inside a functional component like this:

  const [ posts, setPosts ] = useState<Posts[]>()
  
  useEffect(() => {
    getPosts().then((res) => {
      setPosts(res)
    }) //HERE
  }, [])

Pretty basic, i don't see anything wrong but compile doesn't agree with me.

Line 40:4: Parsing error: Expression or comma expected

Any hint?

Posts from localStorage:

"[{"title":"Chocolate Pistachio Cheesecake","body":"This recipe is for a reduced-fat cheesecake made with chocolate wafer cookies, pistachios, avocado, and Greek-style yogurt. The crust is made by pulsing chocolate wafer cookies, pistachios, and sugar in a food processor, and then pressing the mixture into the bottom of a springform pan. The filling is made by blending pistachios, cream cheese, avocado, yogurt, cornstarch, and sugar in a large bowl, and then adding egg whites, almond extract, and a pinch of salt. The cheesecake is then baked and cooled before being topped with a mousse made from whipping cream, powdered sugar, vanilla, and yogurt. The cheesecake is chilled for at least 4 hours before serving and garnished with additional whipped topping and pistachios.","comments":[{"author":"John Doe","content":"Nothing like a good workout to set the tone for the day. Keep up the great work! #motivation #fitnessgoals"},{"author":"Jane Smith","content":"This is another comment on the post."}],"likes":[{"author":"Brad Pit"}]},{"title":"Example post Title","body":"This is the body of the example post. It can contain any text.","comments":[{"author":"John Doe","content":"This is a comment on the post."},{"author":"Jane Smith","content":"This is another comment on the post."}],"likes":[{"author":"Tom Holland"}]}]"

CodePudding user response:

what is the use of async await in JSON.parse(localStorage?.getItem('Posts') || "{}")?? use like this as

 const getPostsFromStorage = () => {
    return JSON.parse(localStorage.getItem('Posts'));
};

and then use it like const posts = getPostsFromStorage() || ""

CodePudding user response:

Somehow i moved the file from ./srcto ./src/components and the error went away. Don't know why.

  • Related