anjali sirsam
anjali sirsam

Reputation: 11

Uncaught SyntaxError: "[object Object]" is not valid JSON at JSON.parse (<anonymous>)

Uncaught SyntaxError: "[object Object]" is not valid JSON
    at JSON.parse (<anonymous>)  
vendors~main.chunk.js:32926 The above error occurred in the <Home> component:

    at Home (http://localhost:3000/static/js/main.chunk.js:1640:99)
    at RenderedRoute (http://localhost:3000/static/js/vendors~main.chunk.js:131876:5)
    at Routes (http://localhost:3000/static/js/vendors~main.chunk.js:132298:5)
    at App
    at Router (http://localhost:3000/static/js/vendors~main.chunk.js:132236:15)
    at BrowserRouter (http://localhost:3000/static/js/vendors~main.chunk.js:130557:5)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
console.<computed> @ vendors~main.chunk.js:32926
localhost/:1 Uncaught (in promise) SyntaxError: "[object Object]" is not valid JSON
    at JSON.parse (<anonymous>)
    at Home (main.chunk.js:1643:72)

VM23:2 Uncaught ReferenceError: process is not defined

CODE

const Home = () => {
  const scrollRef = useRef(null);
  const userInfo = localStorage.getItem('user') !== 'undefined' ? JSON.parse(localStorage.getItem('user')) : localStorage.clear();
  useEffect(() => {
    const query = userQuery(userInfo?.sub);

    client.fetch(query).then((data) => {
      setUser(data[0]);
    })
  }, []);

  useEffect(() => {
    scrollRef.current.scrollTo(0, 0);
  }, [])

Upvotes: 1

Views: 13986

Answers (3)

Gep Sher
Gep Sher

Reputation: 27

For more accurate localization of the error, more info is needed. If we assume that an error occurs during JSON.parse(localStorage.getItem('user')), then it is because Object was used during writing. Local Storage added Object data : localStorage.setItem('user', data) ( fulfilled our order)

localStorage.getItem(data) // output 👉: [object Object] JSON.parse(localStorage.getItem('user')) // output 👎 "[object Object]" is not valid JSON

repair:

localStorage.setItem('user',JSON.stringify(data));

or:

localStorage['user'] = JSON.stringify(data);

Upvotes: 0

Kartoos
Kartoos

Reputation: 1160

Seems like you are getting string "[object Object]" from the localStorage.getItem('user') which basically is useless. Keep in mind localstorage act as dictionary but ONLY stores strings not objects. As @Naman Agrawal pointed out, convert your data to string before storing it into localstorage

localstorage['user'] = JSON.stringify(data)

Upvotes: 1

Naman Agrawal
Naman Agrawal

Reputation: 71

while you are storing the data in the local storage use JSON.stringify(data) instead of directly storing the data.

Upvotes: 4

Related Questions