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

0

115
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
9 months 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();
9 months 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.

9 months 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.

9 months 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 job Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.