skip to Main Content

Take a look at the code below,
Question is, Why a new list item is not getting added on click of "Add to List" ?

function SuperList(props) {
  const liVals = [{name:"One"}, {name:"Two"}, {name:"Three"}, {name:"Four"}, {name:"Five"}];
  const [liValues, up] = useState(liVals);
  function AddToList() {
      liValues.concat({name:"Six"});
      liValues.push({name:"Six"});
      alert(liValues.map(el => "  " + el.name));
      up(liValues);
}

  return (<>
    <ul>
      {liValues.map((l) => <li>{l.name}</li>)}
      </ul>
      <button onClick={AddToList}>Add to List</button>
    </>
  );
} 


createRoot(document.getElementById('root')).render(
      <>
      <SuperList/>
      </>
); 

3

Answers


  1. Chosen as BEST ANSWER
    function SuperList(props) {
      const liVals = [{name:"One"}, {name:"Two"}, {name:"Three"}, {name:"Four"}, {name:"Five"}];
      const [liValues, up] = useState(liVals);
      const AddToList = () => {
        up((state)=> [...state, {name: "Six"},{name: "Seven"}]);
      }
      return (<>
        <ul>
          {liValues.map((l) => <li>{l.name}</li>)}
          </ul>
          <button onClick={AddToList}>Add to List</button>
        </>
      );
    }
    

  2. Because you are mutating the array, React will render whenever the state values changed by non mutation only. So every time you will create new array instead of mutating like you does, create new array using spread operator.

    More information about mutation HERE

    function SuperList(props) {
      const liVals = [{name:"One"}, {name:"Two"}, {name:"Three"}, {name:"Four"}, {name:"Five"}];
      const [liValues, up] = useState(liVals);
      function AddToList() {
          const newValues = [...liValues,{name:"Six"},{name:"Six"}];//non mutable updates
          up(newValues);
    }
    
      return (<>
        <ul>
          {liValues.map((l) => <li>{l.name}</li>)}
          </ul>
          <button onClick={AddToList}>Add to List</button>
        </>
      );
    } 
    
    
    createRoot(document.getElementById('root')).render(
          <>
          <SuperList/>
          </>
    ); 
    
    Login or Signup to reply.
  3.   function AddToList() {
          up((prevState) => {
            let newState = [...prevState, { name : "six"}]
            return [...newState];
          });
       }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search