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
It is showing false because
bioData[0].id
is a number but what you get frominput_id.value
is a string. Input elements always return a string, even fortype="number"
. type attribute is just there for ease of input, it does not parse data in any way. either useparseInt()
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
For this you should write the given code
instead of
because the mongodb has the id of the element as _id.