Home > Enterprise >  SyntaxError: Unexpected end of JSON input while fetchinbg local storage
SyntaxError: Unexpected end of JSON input while fetchinbg local storage

Time:07-26

I am suffering from this error, really do not know what to do at this point. Aparently this error is returning because the localstorage is empty.

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at index.tsx:52:32
    at d (regeneratorRuntime.js:86:17)
    at Generator._invoke (regeneratorRuntime.js:66:24)
    at Generator.next (regeneratorRuntime.js:117:21)
    at r (asyncToGenerator.js:3:20)
    at l (asyncToGenerator.js:25:9)
    at asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at asyncToGenerator.js:21:12
    
    interface IchartData {
        chain: any,
        address: string,
        dex: any,
    }

    const [ items, setItems ] = useState<IchartData>({chain: '', address: '', dex: ''})

    const getLocalStorage = async () => {
        try {         
            const items = await JSON.parse(localStorage?.getItem('ChartData') || "")
            return items     
        } catch (error) {
           console.log(error) 
        }
    }

    getLocalStorage().then((res) => setItems(res))

I'm using this code to avoid the localStorage to be empty but without success


  useEffect(() => {
    const chartData = {chain: '', address: '', dex: ''}
    if(window.localStorage === undefined){
       localStorage.setItem('ChartData', JSON.stringify(chartData))
    }
  }, [])

CodePudding user response:

Your issue is probably because you are passing an empty string if 'ChartData' is undefined in the JSON.parse. Try adding an empty object to a string.

const items = await JSON.parse(localStorage?.getItem('ChartData') || "{}")

CodePudding user response:

If you are using a value in your rendering that might be undefined during initial loading of the page (before the useEffect gets executed in your case), you should save a boolean as a loading state and conditionally render your component so that whenever your loading state is true, you render a generic component without data.

You can then set the loading state to false in the final line of your useEffect to cause a re-render, this time with the value loaded in memory and ready.

  • Related