skip to Main Content

Actually I am trying to set a

elements innerHTML to some value from local storage ,It shows the value for the first time but whenever I trying to reload the page it shows error like the screenshot below!

Error showing after reload

here is the code-

const getName = window.localStorage.getItem("name");

   if(getName.charAt(0) == "M"){
  document.getElementById("myidname").innerHTML = "some message";

   }else{
console.log("error")
   }

<p id='myidname'></p>

I tried to wrap statements into a method then using that method inside the

element but still showing same error.

2

Answers


  1. The error you’re encountering likely stems from trying to manipulate the DOM directly in React before the component has fully mounted, which can lead to accessing elements that do not yet exist. Additionally, when you reload the page, if the localStorage item "name" is not set or is empty, trying to call .charAt(0) on null or undefined will throw an error.

    React recommends a more declarative approach to DOM manipulation, favoring state and props over direct manipulation. To achieve your goal while adhering to React’s best practices, you can use component state and the useEffect hook to read from localStorage and conditionally render content based on that value.

    Here’s a revised approach that avoids direct DOM manipulation and error:

    import React, { useState, useEffect } from 'react';
    
    function MyComponent() {
      const [nameMessage, setNameMessage] = useState('');
    
      useEffect(() => {
        const getName = window.localStorage.getItem("name");
    
        // Check if getName is not null or undefined before attempting to access it
        if (getName && getName.charAt(0) === "M") {
          setNameMessage("some message");
        } else {
          console.log("error or name does not start with M");
        }
      }, []); // Empty dependency array means this effect runs once on mount
    
      return (
        <p id='myidname'>{nameMessage}</p>
      );
    }
    
    export default MyComponent;
    
    Login or Signup to reply.
  2. To avoid this issue, you should check if getName is not null or undefined before trying to access its properties. You can follow code:

    const getName = window.localStorage.getItem("name");
    if (getName && getName.charAt(0) == "M") {
        document.getElementById("myidname").innerHTML = "some message";
    } else {
        console.log("error");
    }
    

    By following these few steps, you ensure that you handle cases where the local storage value may not exist or may not have the expected format.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search