dimanche 25 octobre 2020

How to organize async fetching code in Reactjs

In many components, I need to fetch some data and I'm ending up with a lot of similar code. It looks like this:

const [data, setData] = useState();
const [fetchingState, setFetchingState] = useState(FetchingState.Idle);

useEffect(
    () => {
        loadDataFromServer(props.dataId);
    },
    [props.dataId]
);

async function loadDataFromServer(id) {
    let url = new URL(`${process.env.REACT_APP_API}/data/${id}`);
    let timeout = setTimeout(() => setFetchingState(FetchingState.Loading), 1000)
    try {
        const result = await axios.get(url);
        setData(result.data);
        setFetchingState(FetchingState.Idle);
    }
    catch (error) {
        setData();
        setFetchingState(FetchingState.Error);
    }
    clearTimeout(timeout);
}

How can I put it into a library and reuse it?

Aucun commentaire:

Enregistrer un commentaire