I have a react native web app with expo. And I call at the moment the api call from localhost. But I also have a remote server with of course a other url. How to change the api call for producion?
So I installed
"react-native-dotenv": "^3.4.9",
And I created two env files: dev and production:
.env
GENERATE_SOURCEMAP=false
REACT_APP_NAME=dev
API_URL=http://127.0.0.1
env.prod
REACT_APP_ENV=PRODUCTION
API_URL=https://dierenwelzijndocker.azurewebsites.net
And I changed the babel.config.js file:
/* eslint-disable comma-dangle */
/* eslint-disable prettier/prettier */
module.exports = function (api) {
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: [
"babel-plugin-styled-components-react-native-web",
[
"module:react-native-dotenv",
{
envName: "APP_ENV",
moduleName: "@env",
path: ".env",
blocklist: null,
allowlist: null,
safe: false,
allowUndefined: false,
verbose: false,
},
],
],
};
};
and this is the api call:
import { API_URL } from "@env";
export const loginRequest = async (email, password) => {
try {
const response = await fetch(`${API_URL}/api/user/token/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: email,
password: password,
}),
});
const data = await response.json();
if (response.ok) {
await AsyncStorage.setItem("Token", data.token);
//
return true;
} else {
throw new Error(data.token);
}
} catch (error) {
error, "email en of wachtwoord is niet goed ingevuld";
}
};
and so this works for local development.
But if I to production. I build a web-build folder with the command > npx expo export:web
and a folder web-build has been created in the root folder. but the api calls are still for localhost.
Question: how to change the api call from local to production?
2
Answers
As written in the documentation you can overwrite the environment used with your package.json command
example,
you might have a DEV_API_URL for local development and a PROD_API_URL for
production.
environment variables based on the environment.
(development or production). You might switch between these
configurations during build time or dynamically based on the runtime environment.
config.js: