skip to Main Content

Had an Array, have an update Array function, input will be taken through Form.
Upon Input of ID,I want to check if the ID already exist in the array

Have given input as 1 ,which should give true.

It is showing "false" in console.

  const bioData = [
    {id:1}
   ]

const [myArray, setmyArray] = useState(bioData);
const [sid, setId] = useState("");
const handleID = (e) => {
  setId(e.target.value);
}
const updateArray = () =>{
 
 
  const isFound = myArray.some(el => el.id === sid);

  console.log(isFound);

  if (isFound) {
    console.log('✅ array contains object with id = 1');
  }
}

<input type="number" placeholder='Please enter your ID' className='inputelm' onChange={handleID} />
<button className='addbtn btn inputelm' onClick={updateArray}>Add</button>

2

Answers


  1. It is showing false because bioData[0].id is a number but what you get from input_id.value is a string. Input elements always return a string, even for type="number". type attribute is just there for ease of input, it does not parse data in any way. either use parseInt() when getting the value from input or change the Initial_data to contain id as a string.
    Check the app.js file in the codesandbox below, I have implemented the code here:
    https://codesandbox.io/s/svgfill-3-forked-nzjdc3?file=/App.js

    Login or Signup to reply.
  2. For this you should write the given code

    const isFound = myArray.some(el => el._id === sid);
    

    instead of

    const isFound = myArray.some(el => el.id === sid);
    

    because the mongodb has the id of the element as _id.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search