Tengo 2 ganchos personalizados. 1 para PONER datos, el otro para OBTENER los datos. Necesito recuperar los datos inmediatamente después de que se hayan PUESTO para enrutar al usuario y manejar cualquier error. Con lo que tengo a continuación, las acciones suceden rápidamente y GET sucede antes que PUT. ¿Alguna forma de evitar esto?
const { update, fetch, data, loading, success } = useFoo(data); const OnClickHandler = () => { update(); if (success === 200) { fetch(); // do some checks and if ok route } else { // do something else } }; const fetch = useCallback(() => { setLoading(true); axios({ url: url, headers: foo, method: "get" }) .then((response) => { setLoading(false); setSuccess(response.status); setData(response.data); }) .catch((error) => { setLoading(false); }); }, [setSuccess]); const update = useCallback(() => { setLoading(true); axios({ url: url, headers: foo, method: "put", data: data, responseType: "json" }) .then((response) => { setLoading(false); setSuccess(response.status); console.log(response); }) .catch((error) => { setLoading(false); }); }, [data]);Si desea esperar el final de ciertas llamadas, debe marcar la función como asíncrona y esperar la llamada de función.
Traté de anticipar la estructura de su gancho useFoo() , y aquí están mis cambios:
const useFoo = (data) => { const [ loading, setLoading ] = React.useState(false) const [ success, setSuccess ] = React.useState() const [ data, setData ] = React.useState() const [ error, setError ] = React.useState() const fetch = React.useCallback(async () => { setLoading(true) await axios({ url, // TODO: pass your url headers: {}, // TODO: pass your headers method: 'get' }) .then((response) => { setSuccess(response.status) setData(response.data) }) .catch((error) => { setError(error) }) .finally(() => setLoading(false)) }, [ setSuccess ]) const update = React.useCallback( async () => { setLoading(true) await axios({ url, // TODO: pass your url headers: {}, // TODO: pass your headers method: 'put', data, responseType: 'json' }) .then((response) => { setSuccess(response.status) }) .catch((error) => { setError(error) }) .finally(() => setLoading(false)) }, [ data ] ) return { data, fetch, loading, success, update, error } }El componente que usa el gancho podría verse así:
const YourComponent = () => { const { update, fetch, data, success } = useFoo(foo) const onClickHandler = async () => { await update() if (success === 200) { await fetch() // do some checks and if ok route } else { // do something else } } return null } La palabra clave await obliga a la función a bloquearse hasta que finaliza la llamada a la función.