Home > Back-end >  ReactJS - Add two items to dictionary - Only second one is added
ReactJS - Add two items to dictionary - Only second one is added

Time:10-30

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?

  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

CodePudding user response:

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>

CodePudding user response:

Could it be that you don’t include the current state when assigning a new dictionary and therefore overwriting the state each time?

CodePudding user response:

You've not updated the local dict object, which means you discard the first addition when you make subsequent additions. Instead, do:

const addItem = (name, value) => {
  setDict(dict = {...dict, [name]: value });
};
  • Related