react hook conditional useState - JSON.parse(...) is null

Viewed 593

I am using react hook and I want to retrieve some information from the client's local storage if it exists.

Below is the application state I defined:

const [name, setName] = useState(JSON.parse(localStorage.getItem("personalInfo")).name || "");

I expect that if there is no data in the local storage then an empty string would be used as the initial state.

However, it produces an error: TypeError: JSON.parse(...) is null

It shows that even if local storage is empty, the empty string is still not be used as the initial state.

It works as expected before but after I added in some complex code in another components, it starts to produce errors. Any idea why this can happens so that I know where to debug?

1 Answers

You can use

const localStore = localStorage.getItem("personalInfo")
const [name, setName] = useState(localStore ? JSON.parse(localStore).name : "");

or you can safely parse JSON

function parseJson(){
    try {
      return JSON.parse(localStorage.getItem("personalInfo")).name;
    } catch(ex){
      return "";
    }
}

const [name, setName] = useState(parseJson();
Related