Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

285
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda