0

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>
  );
};
Anit
  • 11
  • 2
  • Does this answer your question? [React.useState does not reload state from props](https://stackoverflow.com/questions/54865764/react-usestate-does-not-reload-state-from-props) – OFRBG Mar 26 '22 at 12:52

1 Answers1

0

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.

  • Thank you .But could u tell me why it's not working and why data_ is blank array and prevData contains element isn't this correct that useState return previous State value?? – Anit Mar 26 '22 at 12:01
  • Because when you remove an item, only the state variable _data is changed, not the parent's data (props.data here is parent's). In the rmData function, you work with props.data that is never changed instead of the data_ which is your state variable. Thus, you always set the previous data value as you current data value and never actually update it. – Stratis Dermanoutsos Mar 26 '22 at 12:08
  • for a moment if i dont't consider rmData function and only render components receiving from the parent const [data_, setData] = useState(props.data); and map over the data_ only then why it's blank an array that's my querry – Anit Mar 26 '22 at 12:15
  • `useState`'s default value setter is only called once on mount. If you want to update the list when props change you need to use `useEffect`. – OFRBG Mar 26 '22 at 12:50