skip to Main Content

using useState and useEffect hooks, i stored my array in local storage.

    const data = window.localStorage.getItem("arrKey")

    const [arr, setArr] = useState(data || [])

    useEffect(() => {
        if (data) {
            setArr(JSON.parse(data))
        }
    }, [])

    useEffect(() => {
        window.localStorage.setItem("arrKey", JSON.stringify(arr))
    },[arr])

i also want to display it on my page. everytime a new user input gets pushed to the array, it supposed be added to the displayed list items. now if i display the array as a whole, it works just fine. but when i try to display the elements one by one with the map function, i get this error:

here is my code:

    return (
        <>
            <form onSubmit={handleSubmit}>
                <h2>Enter numbers</h2>
                <input type={"number"} name={"newnum"}/>
            </form>
            <ul>
                {arr.map(num => (
                    <li>{num}</li>
                ))}
            </ul>
        </>
    )

2

Answers


  1. My assumption is that at some point in the lifecycle, arr is null before it’s populated. It should be able to be solved by adding a default or a guard condition in your JSX.

    {arr && arr.map(num => (
      <li>{num}</li>
    ))}
    
    Login or Signup to reply.
  2. const [arr, setArr] = useState(data || [])
    

    This will assign the string value of data to arr.

    Since strings don’t have the map, you’ll get that error.

    You could just assign an empty array to the useStat, then your logic inside the useEffect will assign the actual array to the useState, and skip the string variant. So use useState([])


    You could also do the JSON.parse on data, then your current useState will work as expected

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