• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

225
Views
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
almost 3 years ago · Juan Pablo Isaza
3 answers
Answer question

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();
almost 3 years ago · Juan Pablo Isaza Report

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.

almost 3 years ago · Juan Pablo Isaza Report

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.

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error