localstorage getitem returning undefined value

Viewed 38

I am developing an app in react. I have a state recordTime which i am initialising with a function which is retrieving localstorage object. I tried to console log the return value from localstorage as well as state object value but i am getting undefined for values returned from localstorage. I am also getting [object object] for state object.

My state looks like below and i am console logging its value which is giving me [object object], i am not sure why though.

    const [recordTime, setRecordtime] = useState(() => fetchPrevioustime())
    console.log(recordTime+"first render")

This is calling below function where i am getting items from local storage and console logging it but it is showing undefined.

function fetchPrevioustime(){
        const recordedTime = JSON.parse(localStorage.getItem(("recordTime")))
        const mnt = (recordedTime.sc)
        console.log(mnt + "fetchfunction")
        if(recordedTime !== null){
            return{
                mn: mnt,
                sc: recordedTime.sc
            }
            
        }
    }

Below is the code where i am setting my local storage which i think is working as expected, it is setting minutes and seconds as an abject inside recordTime localstorage key.

useEffect(() => {
            if(tenzies){
               let temp1 = {
                mn: mn,
                sc: sc
            }
            localStorage.setItem("recordTime", JSON.stringify(temp1))
        }    
    },[tenzies]
    )

So can someone help why i get undefined for this console.log(mnt + "fetchfunction") inside fetchprevioustime function and [object object] as the output for console.log(recordTime+"first render") after initialising the state.

below is my console screenshot - enter image description here

0 Answers
Related