skip to Main Content
function App() {
  // const item = 'mango';
  const itemList = [];
  const [item, updateItm] = useState();

  // listening to onChange of input.
  const listenInput = function (e) {
    // insert item to list
    updateItm(e.target.value);
  }

  const addItem = function() {
    let pv = item;
    itemList.push(pv);
    console.log(itemList);
  }

  return (
    <>
      <div className='main-div'>
        <div className='center-div'>
          <h1>To Do</h1>
          <input
            onChange={listenInput}
            type='text'
            name='item'
            placeholder='Add item'
          />
          <button onClick={addItem}>+</button>
          <ol>
            <li>{item}</li>
          </ol>
        </div>
      </div>
    </>
  );
}

i need it to append the itemList with value of pv.
but every time i enter new value in input it replaces the older value.

What i get
let say pv = 'mango'. then itemList = ['mango'] again when i set pv = 'apple' thn itemList = ['apple']

What i want

let say pv = 'mango'. then itemList = ['mango'] again when i set pv = 'apple' thn itemList = ['mango','apple']

2

Answers


  1. Chosen as BEST ANSWER

    i got it. For every updation by useState it re-render the App() function thus re innitializing the itemList so every time i update item my App() reload and set itemList to null.


  2. You should append the value to the itemList array in the addItem function when the user clicks the button.

    import React, { useState } from 'react';
    
    function App() {
      const [item, updateItem] = useState('');
      const [itemList, updateItemList] = useState([]);
    
      // Listening to onChange of input.
      const listenInput = function (e) {
        // Update the item state with the current input value.
        updateItem(e.target.value);
      }
    
      // Add item to the list when the button is clicked.
      const addItem = function(){
        if (item.trim() !== '') { // Check if the input is not empty
          // Append the current item value to the itemList.
          updateItemList([...itemList, item]);
          // Clear the input field.
          updateItem('');
        }
      }
    
      return (
        <>
          <div className='main-div'>
            <div className='center-div'>
              <h1>To Do</h1>
              <input
                onChange={listenInput}
                type='text'
                name='item'
                placeholder='Add item'
                value={item} // Bind the input value to the state variable
              />
              <button onClick={addItem}>+</button>
              <ol>
                {itemList.map((listItem, index) => (
                  <li key={index}>{listItem}</li>
                ))}
              </ol>
            </div>
          </div>
        </>
      );
    }
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search