Search code examples
urlnext.js

Can't replace api url in next.js


I'm trying to replace api url after changing state of the checkbox.I can see right url in console but in request url steel the same,but it does't throw any error.

export const createServerUrl = (isDev?: boolean) => {
  let url;
  if (isDev) {
    url = 'https://api.majordom-dev.parker-programs.com/v1/';
  } else {
    url = 'https://api.majordom.parker-programs.com/';
  }
  console.log(url);
  return url;
};
export const api = axios.create({
  baseURL: createServerUrl(),
}); 
 const [isDev, setIsDev] = useState(false);
  
  useEffect(() => {
    createServerUrl(isDev);
  }, [isDev]);
 <input type="checkbox" onInput={() => setIsDev((prev) => !prev)}/>

this is my code

I was trying to change url directly in axios.create via ternary operator and also to use different variables but it always succesfully works only in console,not in request.

I will be very appriciated for any help!


Solution

  • The issue you're facing is: axios instance is created once when the module is first imported, and it doesn't react to changes in your state (isDev). To solve this, you need to create a new axios instance each time the isDev state changes. Here’s how you can achieve this:

    const createServerUrl = (isDev) => {
      return isDev
        ? 'https://api.majordom-dev.parker-programs.com/v1/'
        : 'https://api.majordom.parker-programs.com/';
    };
    
    const App = () => {
      const [isDev, setIsDev] = useState(false);
      const [api, setApi] = useState(null);
    
      // useEffect hook to create a new axios instance whenever isDev changes
      useEffect(() => {
        const apiInstance = axios.create({
          baseURL: createServerUrl(isDev),
        });
        setApi(apiInstance);
      }, [isDev]); 
    

    Hope this helps