Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReactJS – Add two items to dictionary – Only second one is added

I’m trying to add 2 items to a dictionary state at once, but only the second one is added.

I made an example below, you can also check the codesandbox. When I run add2Items, only "Item2" is added.

Can anyone tell me what’s going wrong here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const [dict, setDict] = useState({});

  const addItem = (name, value) => {
    console.log("name", name);
    const newItem = { [name]: value };
    const newDict = Object.assign({}, dict, newItem);
    setDict(newDict);
  };

  const add2Items = () => {
    addItem("Item1", "test1");
    addItem("Item2", "test2");
  };

https://codesandbox.io/embed/brave-mountain-ienzbu

>Solution :

Your messages becomes stale for second call of setMessages. To get rid of it use the callback function with setMessages:

  const addMessage = (name, value) => {
    setMessages(prevMessages => ({...prevMessages, [name]: value}));
  };
function MyFunction() {
  const [messages, setMessages] = React.useState({});

  const addMessage = (name, value) => {
    setMessages(prevMessages => ({...prevMessages, [name]: value}));
  };

  const add2Messages = () => {
    addMessage("Message1", "test");
    addMessage("Message2", "test2");
  };

  return (
    <div>
      {JSON.stringify(messages)}
      <button onClick={() => add2Messages()}>Add 2 messages</button>
    </div>
  );
}

ReactDOM.render(<MyFunction />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading