Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

662
Views
¿Cómo puedo usar el gancho useFetch cuando se hace clic en un botón?

Estoy tratando de hacer una solicitud usando useFetch del paquete npm react-fetch-hook cuando se presiona un botón. Aquí está mi código

 import React, { useState } from 'react'; import useFetch from 'react-fetch-hook'; import { Button } from 'react-bootstrap'; const Component = () => { const [message, setMessage] = useState(false); const handleOnClick = () => { const { isLoading, data } = useFetch( 'https://raw.githubusercontent.com/markmclaren2/sample_json/main/user.json' ); if (isLoading) { setMessage('Loading...'); } else { setMessage(`Received id: ${data.id}`); } }; return ( <div> <Button onClick={handleOnClick}>Load Data</Button> <div>{message}</div> </div> ); }; export default Component;

encontré este error

React Hook "useFetch" is called in function "handleOnClick" that is neither a React function component nor a custom React Hook function.

¿Cuál es la forma correcta de llamar a useFetch cuando el usuario presiona el botón y muestra "Cargando..." y luego los mensajes de resultado?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

useFetch es un gancho que envuelve el método fetch() global. Se considera como un React Hook personalizado por react debido a su nombre

Los ganchos personalizados son más una convención que una característica. Si el nombre de una función comienza con "uso" y llama a otros Hooks, decimos que es un Hook personalizado.

Por lo tanto, la ubicación debe seguir las reglas de los ganchos personalizados de React, ya sea en un componente de función de React o en una función de Hook de React personalizada.

Como dice el documento , podemos usar las opciones depends para activar la recuperación.

La solicitud no se llamará hasta que todos los elementos de la matriz de dependencias sean veraces.

Por lo tanto, podemos implementar esto usando el estado isClicked como el activador de obtención donde el estado isClicked se restablecerá mediante ganchos useEffect . Por lo tanto, en cada evento de clic, useFetch realizará una nueva solicitud al servidor.

CódigoSandbox

 import React, { useEffect, useState } from 'react'; import useFetch from 'react-fetch-hook'; const Component = () => { const [isClicked, setIsClicked] = useState(false); const [message, setMessage] = useState(''); // place the useFetch hooks here as the rules says const { isLoading, data } = useFetch( 'https://raw.githubusercontent.com/markmclaren2/sample_json/main/user.json', { depends: [isClicked] } ); useEffect(() => { isClicked && setIsClicked(false); },[isClicked]); useEffect(() => { if (isLoading) { setMessage('Loading ...'); } if (data && !isLoading) { setMessage(`Received id: ${data.id}`) } },[data, isLoading]) return ( <div> <button onClick={() => setIsClicked(true)}>Load Data</button> <div>{message}</div> </div> ); }
about 4 years ago · Santiago Gelvez Report

0

Hola tal vez haga algo como esto:

 import React, { useState } from "react"; import useFetch from "react-fetch-hook"; import { Button } from "react-bootstrap"; export default function App() { const [message, setMessage] = useState(""); const [isClicked, setIsClicked] = useState(false); const { isLoading, data } = useFetch( "https://raw.githubusercontent.com/markmclaren2/sample_json/main/user.json", { depends: [isClicked], formatter: (response) => response.text() } ); const handleOnClick = () => { setIsClicked(true); if (isLoading) { setMessage("Loading..."); } else { setMessage(data as string); } }; return ( <div> <Button onClick={handleOnClick}>Load Data</Button> <div>{message}</div> </div> ); }

También preparé un codeandbox aquí para que puedas comprobarlo.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!