I'm trying to update some content on the screen upon a change in the data. I'm using React function component with hooks. When the data is updated in the parent element, I send it via props to PlayerControls
:
export const PlayerControls = (props) => {
....
const [heatmaps, setHeatMaps] = React.useState("");
const [data, setData] = React.useState(null);
useEffect(fetchData, [props.videoData]);
useEffect(updateHeatmaps, [data]);
function fetchData () {
d3.csv(require(`./data/${props.videoData}`)).then((d) => setData(d));
}
function updateHeatmaps(){
if (data && data.length) {
const temp = data.map((item, index) => {
return (
<Heatmap size={[400, 50]} data={item} key={index}/>
)
});
setHeatMaps(temp);
}
}
return (
<div>
{heatmaps}
</div>
);
}
The problem is, although this works properly for the initial data, it does not update heatmaps
on the screen. Now, I'm familiar with the fact that setState
hook is asynchronous and there are solutions (such as using the useEffect
hook to update the state and add the state as a dependency), e.g., this StackOverflow question. The problem is I'm updating the state withing another function and I cannot use useEffect
there or in the return function. I would really appreciate any solutions, this problem has been dragging me along for a while now, makes me wonder if these hooks and function components are a solution for all the use cases or not.