'I'm trying to pass updating data from parent to child in react, but it's not updated in function of child component

I want to pass the data from parent component to child component, and update this data in the child component every time it’s updated in the parent component.

I'm updating scrollY data every time I scroll in the parent component, and I try to pass it to the child component.

export default function Parent() {
  let [scrollY, setScrollY] = useState(0);

  useEffect(() => {
    function onScroll(e) {
      setScrollY(window.scrollY);
    }

    window.addEventListener("scroll", onScroll);

    return () => {
      window.removeEventListener("scroll", onScroll);
    };
  });

  return (
    <Child scrollY={scrollY} />
  );
}

In child component, I want to use received data in animation frame function. I tried to console the received scrollY data in animation frame function and also print out it in html to check if passed data is updating properly.

export default function Child(props) {
  useEffect(() => {
    function onScroll() {
      console.log(props.scrollY);
    }

    function step() {
      console.log(props.scrollY);

      animationFrame = window.requestAnimationFrame(step);
    }

    window.addEventListener("scroll", onScroll);
    let animationFrame = window.requestAnimationFrame(step);

    return () => {
      window.removeEventListener("scroll", onScroll);
      window.cancelAnimationFrame(animationFrame);
    };
  });

  return (
    <div>{props.scrollY}</div>
  );
}

in html, the data is keep updating, but in console, it only prints out '0'. what I can't understand is data in return {props.scrollY} is updated, but data in function is not updated. what did I do wrong? how can I get updating data value also within the function?



Solution 1:[1]

it's the nature of console.log() that it shows the previous state/data(value) please use alert() instead to check your data like:

alert(props.scrollY)

Solution 2:[2]

Read csv using pandas, using following function

pandas.read_csv()

It will read list as string. To convert it into list use following function

import ast

ast.literal_eval()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dawood Ahmad
Solution 2 Rohit Raj