0

The array in the following code is not updating properly.

The following is the code,

const { useState, useRef, useEffect } = React;

/*export default*/ function App() {
    const [array, setarray] = useState([]);
    const Add = () => {
        console.log(one.current.value);
        setarray((e) => {
            return [one.current.value, ...e];
        });
        // Stack Snippets can't use localStorage, but you don't need it
        // to show this problem
        // localStorage.setItem("notes", array);
        console.log("after adding the value -> ", array);
    };
    const one = useRef(null);
    return (
        // <> No need for this fragment, and the version of Babel here on
        // SO is so shockingly outdated it doesn't understand the short form
            <div className="App">
                <h1>Hello CodeSandbox</h1>
                <div className="align">
                    <input ref={one} />
                    <br />
                    <br />
                    <button onClick={Add}>Add</button>
                </div>
                <div className="align"></div>
            </div>
        // </>
    );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

When I am clicking the Add button then the array is not updating, moreover, the array is updating for the first element when I am clicking the second time.

And the second is updating after the third click.

What is wrong here? Following is the code sandbox link.

https://codesandbox.io/s/silly-neumann-b0foos?file=/src/styles.css

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Ankit
  • 1,359
  • 1
  • 2
  • 15
  • I've copied your code into an **on-site** runnable example using Stack Snippets (the `[<>]` toolbar button). Stack Snippets support React, including JSX; [here's how to do one for next time](http://meta.stackoverflow.com/questions/338537/). – T.J. Crowder Oct 27 '22 at 14:02
  • https://codesandbox.io/s/exciting-shadow-xv4s0w?file=/src/App.js i updated the code here. you put the code inside the function so in the same function updated state not display. you need to console outside the function for display the reflected value – Amit Kadivar Oct 27 '22 at 14:04
  • State updates are *asynchronous*, `array` isn't updated because you're looking at the old copy of `array`. If you want to see the updated `array`, log it in render. – T.J. Crowder Oct 27 '22 at 14:04
  • How can I update my localStorage properly? If I will keep it out then after refreshing it will become empty. – Ankit Oct 27 '22 at 16:00

0 Answers0