1

Unable to set state using the function returned from useState hook.

wrapping more functions and logging it at every point possible, it succeeds in asynchronously getting new data all the way down to the setData call which I can't find a way to peak inside. I also checked before render to see if data was changing in state but not in the webpage but the data object doesn't change in value after calling setData.

function PollResults(props) {
  const classes = useStyles2();
  const [data, setData] = useState([]);

  const changeData = data => {
    console.log(data);
    setData(data);
  };

  useEffect(() => {
    subscribeToResults(props.id, data => {
      //console.log(data);
      changeData(data);
    });
    return () => {
      unsubscribeToResults(props.id);
    };
  }, [props.id, setData]);
  //console.log(data);
  return <VictoryPie animate colorScale="qualitative" data={data} />;
}
user3645925
  • 111
  • 1
  • 12

1 Answers1

0

You need to do a simple change at your code:

function PollResults(props) {
  const classes = useStyles2();
  const [data, setData] = useState([]);

  const changeData = data => {
    console.log(data);
    setData([data]); // using [] around value.
  };

  useEffect(() => {
    subscribeToResults(props.id, data => {
      //console.log(data);
      changeData(data);
    });
    return () => {
      unsubscribeToResults(props.id);
    };
  }, [props.id, setData]);
  //console.log(data);
  return <VictoryPie animate colorScale="qualitative" data={data} />;
}

Maybe you will need to check your ChangeData method using hook useCallback to avoid infinite rerender (if this occurs).

Carlos Querioz
  • 277
  • 3
  • 7