i want to use useMemo instead of a local state using javascript, react and graphql.
what i am trying to do?
I am displaying a progress bar based on data fetched from progress query. the fetched data from progress query is set in a state.
below is the code,
const ProgressModal = (status) => {
const [progress, setProgress] = React.useState<>(undefined); //progress state
//setting
const { data: progressData, stopPolling: stopPolling } =
useCheckProgressQuery({
variables: {id},
pollInterval: 3000,
})
React.useEffect(() => {
if (status === initial) {
setProgress(undefined);
}
if (status===started) {
setProgress(progressData);
}
if (status === finished && completed >= total || status === failed) {
stopPolling();
setProgress(undefined);
}
}, [progress, progressData, setProgress]);
const completed= progress
? progress.Progress.completed : 0;
const total = progress ? progress.Progress.total : 0;
let value = 0;
if (completed > 0 && total > 0) {
value = (completed / total) * 100;
}
return (
<ProgressBar value = {progress} />
);
}
the above code works but how can i use useMemo for above case instead of a local state. could someone help me with this. i am new to using react hooks. thanks.
useMemo and useState with useEffect do different things, so you can not convert useState/useEffect 100 % equally to useMemo.
A more or less equivalent useMemo approach would be this (but it doesn't work, other refactoring would then also be necessary, see below):
const progress = useMemo(() =>{
if( status === initial ){
return undefined;
}
if( status===started ){
return progressData;
}
if( status === finished && completed >= total || status === failed ){
return undefined);
}
return undefined; // <-- you need to define default/fallback
},
[ progressData, status, completed, total ] // <-- some where missing in your example
);
This is not a working solution, more refactoring is required:
stopPolling() is not called, which needs an extra useEffect now.progress depends on completed and total, and completed / total both depend on progress (circular dependencies)