Anit
Anit

Reputation: 11

I am quite confused about React js useState hook

const [data_, setData] = useState(prevData); console.log(data_,prevData); prevData here is an array on the other hand data_ is an empty array i don't understand why as much as i understand useState hook it return two values one of them is previous state value. can any pls explain why data_ is blank?

expample of the project i am trying to create
What i am trying to do is to create dynamic card block[containing info about name and age] and i also want to remove them with the click of clear btn on the corresponding card, so i lifted the data to parent component and here i tried to update the data but it doesn't seems to be working

const PersonList = (props) => {
  let prevData = props.data;
  const [data_, setData] = useState(prevData);
  function rmData(args) {
    let removeItem = props.data.find((el) => el.id == args);
    let removeData = props.data.slice(props.data.indexOf(removeItem));
    setData(removeData);
  }
  return (
    <div className={styles.personList}>
      {data_.map((el) => (
        <Person
          name={el.name}
          age={el.age}
          key={el.id}
          rm={rmData}
          id={el.id}
        />
      ))}
    </div>
  );
};

Upvotes: 0

Views: 148

Answers (1)

Stratis Dermanoutsos
Stratis Dermanoutsos

Reputation: 786

What you can do is declare the state in the parent and pass data and setData as the props to PersonList.

However, for the future, when you become more familiar with how state and hooks work, I'd recommend learning a state management framework like Redux.

Upvotes: 0

Related Questions