Home > Mobile >  Why my map is not returning array elements on the page in real time
Why my map is not returning array elements on the page in real time

Time:10-28

When I am trying to add notes to the todo then the elements are pushing in the array, and I can see the elements in console.

But without refreshing the page I am not able to see the elements.

My local storage implementation is also correct

What is wrong here,

import "./styles.css";
import { useState, useRef, useEffect } from "react";
export default function App() {
  let array = [];
  let notes = localStorage.getItem("notes");
  if (notes !== null) {
    array = JSON.parse(notes);
  }
  const Add = () => {
    array.push(one.current.value);
    localStorage.setItem("notes", JSON.stringify(array));
    console.log("after adding the value -> ", array);
  };
  const one = useRef(null);
  return (
    <>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <div className="align">
          <input ref={one} />
          <br />
          <br />
          <button onClick={Add}>Add</button>
        </div>
        <div className="align">
          {array.map((e, index) => {
            console.log(index, "-> ", e);
            return (
              <div key={index} index={index   1} name={e}>
                {e}
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

This is the codesandbox link

Edit summer-sun-ueukqd

CodePudding user response:

Need to use useEffect, useState to set values to variable

const [array, setArray] = useState([]);
  const one = useRef(null);

  const notes = useMemo(() => localStorage.getItem("notes"), []);

  useEffect(() => {
    if (notes) setArray(JSON.parse(notes));
  }, [notes]);

  const Add = () => {
    setArray((state) => [...state, one.current.value]);
    localStorage.setItem("notes", JSON.stringify(array));

    console.log("after adding the value -> ", array);
  };

Demo

  • Related