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

85
Visualizações
Using Custom hooks in React the right way

I have been having major problems understanding the best approach to using/calling my custom hooks inside a function. in my resent code, I am trying to call a custom fetch hook in my app.js

I want to send the following properties (name and age) to my server to handle database storage there, so i intend to have this action happen when the user clicks a button after filling in their name and age. code below

app.js

const [name, setName] = useState('Owen');
const [age, setAge] = useState(22);

const handleClick = () => {
//if statement to check that name and age where provided
  const {data,error} = useFetchPost('url',{name:name,age:age}); 
}

useFetchPost.js

const useFetchPost = ({url, val}) => {
 
 const [data, setData] = useState(null);
 const [error, setError] = useState(null);

 useEffect(()=> {
  fetch(url,{method:'POST',header: {'Content-Type': 'application/json'}, 
  body:JSON.stringify(val)})
  .then(res =>  return res.json())
  .then(data => setData(data))
  .catch(err => setError(err))
 }, [url, val])

 return { data, error }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Hooks need to be called when the component renders, not when a click happens. But you can have your hook return a function, and then call that function in handleClick. For example:

const useFetchPost = () => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  const doFetch = useCallback((url, val) => {
    fetch(url, {
      method: "POST",
      header: { "Content-Type": "application/json" },
      body: JSON.stringify(val),
    })
      .then((res) => res.json())
      .then((data) => setData(data))
      .catch((err) => setError(err));
  }, []);

  return { data, error, doFetch };
};

// used like:
const App = () => {
  const { data, error, doFetch } = useFetchPost();

  const handleClick = () => {
    doFetch(url, {
      method: "POST",
      header: { "Content-Type": "application/json" },
    });
  };
};

about 4 years ago · Juan Pablo Isaza 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