0
console.log(saveState) //IT RETURNS {user: {lat: -20.8213224, lng: -49.3581463}}
console.log(typeof saveState) //RETURNS "object"
console.log(JSON.stringify(saveState)) //RETURNS {"user":{}}

Why is it happening, what i'm doing wrong? I'm using Javascript

This is the code of the error: I'm trying to take states from localStorage, and send it to redux Storage. I'm coding in Next.JS + Redux

Codes below

app.tsx

import type { AppProps } from 'next/app'
import { localStorageKeys, storeWrapper } from '../store'
import { Provider } from 'react-redux'
import { useEffect } from 'react'
import { userUpdate } from '../store/actions/users'
import GlobalStyle from '../styles/global'
import { Navbar } from '../components/Navbar'
import CategorySelector from '../components/CategorySelector'
import Head from 'next/head'

function App({ Component, pageProps }: AppProps) {
  const {store, props} = storeWrapper.useWrappedStore(pageProps)

  useEffect(()=>{
    let state: any = localStorage.getItem(process.env.NEXT_PUBLIC_STORAGE_KEY||"")
   
    if(state){
        try{
            state = JSON.parse(state)
            if(state.user){
              if(!state.user.lat || !state.user.lng){
                navigator.geolocation.getCurrentPosition((pos)=>{
                  state.user.lat = pos.coords.latitude;
                  state.user.lng = pos.coords.longitude;
                })
              }
            }
            else{
              navigator.geolocation.getCurrentPosition((pos)=>{
                state.user.lat = pos.coords.latitude;
                state.user.lng = pos.coords.longitude;
              })
            }
            
        }catch{
            state = {}
        }
    }else{
        state = {}

        state.user = {}
        
        navigator.geolocation.getCurrentPosition((pos)=>{
          state.user.lat = pos.coords.latitude,
          state.user.lng = pos.coords.longitude
        })
    }

    Object.entries(localStorageKeys).map((val, index)=>{
      const [ref, key] = val
      if(state[ref]){
        switch(ref){
          case 'user':
            store.dispatch(userUpdate(state[key]))
            break
          default:
            break
        }
      }
    })
  })

  return (
    <Provider store={store}>
      <GlobalStyle />
      <Navbar />
      <CategorySelector />
      <Component {...pageProps} />
    </Provider>
  )
}

export default App

Here is the function that isn't working well, when I'm trying to convert the state to string to save, it returns nothing, but when it is in object type, it returns lat and lng properly saveState.ts

export const saveState = (key: string, value: any) => {
    let state: any = localStorage.getItem(keyName)
    console.log("SAVE", key, value)
    if(state){
        try{
            state = JSON.parse(state)
        }catch{
            state = {}
        }
    }else{
        state = {}
    }

    state[key] = value

    const saveState = state

    console.log(saveState)
    console.log(typeof saveState)
    console.log(JSON.stringify({saveState}))
    
    localStorage.setItem(keyName, JSON.stringify(state))
}

I really dont know what to do

Lucas Dias
  • 26
  • 1
  • I've converted your question into a runnable code snippet, where you can observe that the code is working as expected. Please provide a [mcve] which demonstrates the problem you're trying to describe. – David Jan 09 '23 at 15:11
  • @David the code you've added does not reproduce the issue. – VLAZ Jan 09 '23 at 15:11
  • 2
    @David that's obviously not what the object looks like. Your edit is unhelpful – mousetail Jan 09 '23 at 15:11
  • It's obvious that `saveState` is not a normal object, but please [edit] your post to include details where it came from and how it's defined. Otherwise it's impossible for us to tell what is going on. – mousetail Jan 09 '23 at 15:12
  • 1
    @VLAZ: Yes, that's exactly the point. The code shown *doesn't* demonstrate the problem. The OP is encouraged to provide a [mcve] which *does* demonstrate the problem. – David Jan 09 '23 at 15:12
  • @mousetail: Yes, that's exactly the point. The code shown *doesn't* demonstrate the problem. The OP is encouraged to provide a [mcve] which *does* demonstrate the problem. – David Jan 09 '23 at 15:12
  • @David Editing the post with a obviously not reproducible example is not a good way to encourage adding a reproducible example. The post is bad but your edit only made it worse. – mousetail Jan 09 '23 at 15:13
  • @David *your* code makes it a completely different issue. Yes, details are needed but making up obviously wrong ones isn't helpful, either. – VLAZ Jan 09 '23 at 15:14
  • 1
    https://stackoverflow.com/questions/15733878/why-does-json-stringify-not-serialize-non-enumerable-properties might help – Trevor Dixon Jan 09 '23 at 15:16
  • 3
    Either the properties are not enumerable and own. Or, the object is populated with those properties after the stringify line runs (`console.log(saveState)` will show the updated object because it keeps a reference) – adiga Jan 09 '23 at 15:19
  • 1
    The problem is that `navigator.geolocation.getCurrentPosition` updates the user object asynchronously. You're calling `JSON.stringify` before the properties are being created. – Bergi Jan 11 '23 at 08:20

0 Answers0