Answer the question
In order to leave comments, you need to log in
How to implement the ability to reload data in a component on hooks?
There is a hook for getting data:
const useData = ({id, setData}) => {
let canceled = false;
const fetchData = useMemo(() => () => {
new Promise(res => setTimeout(res, 2000))
.then(() => {
if(canceled) return;
console.info('Data fetched!');
setData(['1', '2', '3'])
})
}, [id, setData]);
const cancel = useMemo(
() => () => canceled = true,
[id, setData]
);
return [fetchData, cancel];
};
const DataComponent= () => {
const [id, setId] = useState(10);
const [data, setData] = useState([]);
const [fetch, cancel] = useData({id, setData});
useEffect(() => {
fetch();
return cancel;
}, [fetch, cancel]);
const reload = useCallback(() => {
cancel();
// ... ???
}, [fetch, cancel]);
return (
<div>
<Button onClick={reload}>Reload</Button>
{data.length !== 0 && data.map((item, i) => <p key={i}>{item}</p>)}
{data.length === 0 && <p>No data</p>}
</div>
)
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question