Home > Net >  React, getting Invalid Hook Call inside my service for creating an axios instance
React, getting Invalid Hook Call inside my service for creating an axios instance

Time:06-27

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

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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();
  • Related