Home > Mobile >  React Native, passing locale parameter from i18next to Axios config file gives Invalid hook call err
React Native, passing locale parameter from i18next to Axios config file gives Invalid hook call err

Time:06-05

I'm trying to implement a locale parameter into my axiosConfig file:

import axios from "axios";

const instance = axios.create({
  baseURL: "http://10.0.2.2:8000/api",
  timeout: 2000,
});

instance.defaults.headers.common["locale"] = "en";

export default instance;

On each screen I make my get and post calls on screens as such:

axiosConfig
      .get("/someroute")
      .then((response) => {
        //console.log(response.data);
      })
      .catch((error) => {
        console.log(error.message);
      });

The above code works as intended. Now I want to pass a "locale" parameter into all of my axios calls. This parameter will come from app locale (i use i18next). When I implement it as below, it throws an invalid hook error.

import axios from "axios";
import { useTranslation } from "react-i18next";

const { i18n } = useTranslation();

const instance = axios.create({
  baseURL: "http://10.0.2.2:8000/api",
  timeout: 2000,
});

instance.defaults.headers.common["locale"] = i18n.language;

export default instance;

What would be the correct way to set the locale header in my configuration?

CodePudding user response:

You are getting this error because a hook should be called in a React Component or inside another hook. See Rules of Hooks. And here is what you could do for example:

  1. Transform the file where you are setting the axios instance to a hook:
import axios from "axios";
import { useTranslation } from "react-i18next";

const useAxiosInstance = ()=>{
  const { i18n } = useTranslation();

  const instance = axios.create({
    baseURL: "http://10.0.2.2:8000/api",
    timeout: 2000,
  });
  instance.defaults.headers.common["locale"] = i18n.language;
  
  return instance;
}
export default useAxiosInstance;
  1. You include the hook at the top of the file where you are using the axios config and use it as an example this way:
import {useEffect} from "react";
import useAxiosConfig from "./path";

const AxiosConsumer = ()=>{
 const axiosConfig = useAxiosConfig();
 
 useEffect(()=>{
   axiosConfig
    .get("/someroute")
    .then((response) => {
    //console.log(response.data);
    })
    .catch((error) => {
    console.log(error.message);
    });
  },[axiosConfig]);
  
  return <></>
}
  • Related