Creo un gancho que administra el estado de un solo objeto con fetch to api. Este gancho expone la función para interactuar con este objeto.
// the hook const useMyHook = () => { const [myObject, setMyObject] = useState(null); useEffect(() => { const fetchData = async () => { const data = await fetchSomething(); setMyObject(data); } fetchData(); }, []); const updateMyObject = async () => { console.log(myObject); // log : { ... } try { console.log(myObject); // log : undefined // ... } catch(err) { // ... } }; return { updateMyObject, myObject }; }; Luego uso este gancho dentro de un componente y updateMyObject() con un botón.
// the component const MyComponent = () => { const { myObject, updateMyObject } = useMyHook(); return ( <button onClick={updateMyObject}> Click me </button> ); }; ¿Cómo es posible que antes del bloque try catch el registro esté limpio y dentro del bloque quede undefined ?
¡Tu código está perfectamente bien! Podría haber un problema en el fetchSomething() method . Idealmente, debería devolver datos, pero no está haciendo el mismo trabajo.
Aquí hay un pequeño ejemplo. Puedes darle una oportunidad.
const fetchSomething = async () => { const response = await fetch( "https://jsonplaceholder.typicode.com/posts/1" ).then((res) => res.json()); return response; };creo que esto va a funcionar
useEffect(() => { const fetchData = async () => { const data = await fetchSomething(); setMyObject(data); } If(!myObject) fetchData(); }, [myObject]);