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

290
Visualizações
React, getting Invalid Hook Call inside my service for creating an axios instance

I have a simple service.js that looks like this:

import axios from 'axios'
import { useContext } from 'react'
import APIContext from '../context/api/context'

function GetApi() {
  const { API } = useContext(APIContext)
  console.log(API)
  return API
}

const api = axios.create({
  baseURL: `${GetApi()}`,
})

export default api

Whenever I try to use the API, it throws me an error saying:

Invalid Hook Call. Hooks can only be called inside the body of a function component
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can call a hook, useContext in your case, only in a React component or a custom hook (see Rules of Hooks).

What you can do is to transform your service to a hook:

import axios from 'axios'
import { useContext } from 'react'
import APIContext from '../context/api/context'

function useGetApi() {
  const { API } = useContext(APIContext)
  console.log(API)
  const api = axios.create({
    baseURL: API,
  })
  return api;
}

export default useGetApi;

And you use it inside a component or another hook like this:

const api = useGetApi();
about 4 years ago · Juan Pablo Isaza Relatório

0

The thing you show is function and not a functional component, where a hook should live. You must place hooks in the body of functional components, pass states as props and setters as callbacks if you want to use them if child components.

about 4 years ago · Juan Pablo Isaza Relatório

0

What does APIContext contain? Function component means that you must return jsx, technically a react node. So in your case GetApi is not a react component but a plain funciton.

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