javascript - useState hook not working on updating map - Stack Overflow

I am using a useState hook to store a Mapconst [optionList, setOptionsList] = useState(new Map([[uuidv1

I am using a useState hook to store a Map

    const [optionList, setOptionsList] = useState(new Map([
        [
            uuidv1(), {
                choice: "",
            }
        ]
    ]));

on adding a new option , I call this function

    const handleAddNewOption = () => {
        console.log('reached here');
        optionList.set(uuidv1(), {
            choice: "",
        });
    }

but the list does not re-render on updation

    useEffect(() => {
    console.log("optionList", optionList)    
}, [optionList]);

I am using a useState hook to store a Map

    const [optionList, setOptionsList] = useState(new Map([
        [
            uuidv1(), {
                choice: "",
            }
        ]
    ]));

on adding a new option , I call this function

    const handleAddNewOption = () => {
        console.log('reached here');
        optionList.set(uuidv1(), {
            choice: "",
        });
    }

but the list does not re-render on updation

    useEffect(() => {
    console.log("optionList", optionList)    
}, [optionList]);

Share Improve this question asked Mar 8, 2021 at 6:30 Kuldeep SharmaKuldeep Sharma 211 silver badge3 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You'll need to retrieve the array of entries, then add the new entry to it, and finally construct an entirely new Map.

const handleAddNewOption = () => {
    console.log('reached here');
    const entries = [
        ...optionList.entries(),
        [
            uuidv1(),
            { choice: "" }
        ]
    ];
    setOptionsList(new Map(entries));
}

You also might consider using the callback form of useState so you don't unnecessarily create a new unused Map every render.

Another option to consider is to use an object indexed by uuid instead of a Map, if only for the ease of coding - using Maps with React is a bit more plicated than would be ideal.

React shallow pares the old state and the new state values to detect if something changed. Since it's the same Map (Map's items are not pared), React ignores the update.

You can create a new Map from the old one, and then update it:

const { useState, useEffect } = React;

const uuidv1 = () => Math.random(); // just for the demo

const Demo = () => {
  const [optionList, setOptionsList] = useState(() => new Map([
    [uuidv1(), { choice: "" }]
  ]));

  const handleAddNewOption = () => {
    console.log('reached here');

    setOptionsList(prevList => {
      const newList = new Map(prevList);

      newList.set(uuidv1(), { choice: "" });

      return newList;
    });
  };

  useEffect(() => {
    console.log("optionList", JSON.stringify([...optionList]));
  }, [optionList]);

  return (
    <button onClick={handleAddNewOption}>Add</button>
  );
}

ReactDOM.render(
  <Demo />,
  root
);
<script crossorigin src="https://unpkg./react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg./react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

Leverage the fact that useState can take a function. This function gives you the previous value and it's supposed to return the new value for the state

const [myMap, setMyMap] = useState(new Map())

setMyMap((prevMap) => {
    const nextMap = new Map(prevMap);
    nextMap.set(key, value);
    return nextMap;
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745617701a4636334.html

相关推荐

  • javascript - useState hook not working on updating map - Stack Overflow

    I am using a useState hook to store a Mapconst [optionList, setOptionsList] = useState(new Map([[uuidv1

    8小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信