简体   繁体   中英

useState hook not working on updating map

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]);

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 complicated than would be ideal.

React shallow compares the old state and the new state values to detect if something changed. Since it's the same Map (Map's items are not compared), 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.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM