0

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>

  • When do you call `updateArray`? – Konrad Jun 16 '23 at 15:47
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Konrad Jun 16 '23 at 15:47
  • 1
    What does `myArray` or `sid` contain when this code is executed? If a match is not found then it's not found. The various React bits surrounding this operation are either (1) irrelevant and just a distraction or (2) an important part of the observed result and incomplete in the question. I'm thinking it's likely the latter. Can you provide a runnable [mcve] which demonstrates the problem? – David Jun 16 '23 at 15:50
  • Have Updated check once – Akash Kr. Das Jun 16 '23 at 16:12
  • Welcome to StackOverflow. Your post doesn't match the standards StackOverflow sets. Please read this guide: [How To: Ask good questions](https://stackoverflow.com/help/how-to-ask) Also your issue is in the `updateArray` method. You are trying to access `fname` and `score` however they are not defined. So you need to define them. ALso you should update the state of `myArray` with the new data you get. – AztecCodes Jun 16 '23 at 16:12
  • Have Updated Please read the Questions again. – Akash Kr. Das Jun 16 '23 at 16:22

2 Answers2

2

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.

//Filename: App.js

import { useState, useRef } from "react";

export default function App() {
  const bioData = [{ id: 1, name: "harry", score: 12 }];
  const [myArray, setMyArray] = useState(bioData);
  const [sid, setId] = useState();
  const nameInput = useRef();
  const scoreInput = useRef();

  const handleId = (e) => {
//parseInt(value, radix)
//for decimal number system, radix is 10 
    setId(parseInt(e.target.value, 10));
  };

  const updateArray = () => {
    const new_data = {
      id: sid,
      name: nameInput.current.value,
      score: scoreInput.current.value
    };

    const isFound = myArray.some((el) => {
      return el.id === new_data.id;
    });

    if (isFound) {
      console.log("✅ array contains object with id:", new_data.id);
      return;
    }
    setMyArray([...myArray, new_data]);
    console.log("updated");
  };

  return (
    <form>
      <input
        ref={nameInput}
        type="number"
        placeholder="Enter Id"
        onChange={(e) => handleId(e)}
        required
      />
      <input ref={scoreInput} type="text" placeholder="Enter Name" required />
      <input
        id="input-score"
        type="number"
        placeholder="Enter Score"
        required
      />
      <button
        type="submit"
        onClick={(e) => {
          e.preventDefault();
          updateArray();
        }}
      >
        submit
      </button>
    </form>
  );
}
Aniket Pandey
  • 464
  • 1
  • 9
0

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.