Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

663
Visualizações
How can I use the useFetch hook when a button is clicked?

I am trying to make a request using useFetch from react-fetch-hook npm package when a button is pressed. Here is my code

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;

I encountered this error

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

What is the correct way to call useFetch when the user presses the button and show the "Loading..." and then the result messages?

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

useFetch is a hooks that wrap global fetch() method. It is considered as a custom React Hook by react because of its name

Custom Hooks are more of a convention than a feature. If a function’s name starts with ”use” and it calls other Hooks, we say it is a custom Hook.

So, the placement has to follow react custom hooks rules whether in a React function component or in a custom React Hook function.

As the document says that we can use depends options to trigger the fetch.

The request will not be called until all elements of depends array be truthy.

So, we can implement this by using isClicked state as the fetch trigger where the isClicked state will be reset by useEffect hooks. So, on every click event, the useFetch will make a new request to the server'

CodeSandbox

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 Relatório

0

Hello maybe do something like this:

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

I also prepared a codesandbox here so you can check it out

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda