I
I
Ilya Pavlov2019-09-30 13:24:29
React
Ilya Pavlov, 2019-09-30 13:24:29

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];
};

And also there is a component that uses it:
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>
    )
};

It is necessary to add the ability to reload the data with the Reload button at any time. Accordingly, if I simply call cancel() and then fetch() in reload(), then this fetch will already be canceled. How can you do this with hooks?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question