I am new to react-typescript, I have created the .env file named as process.env inside the src folder. Where I have given my url as REACT_APP_API_ENDPOINT=http://localhost:8080/prices
In my App.tsx I have use that as follows:
const { REACT_APP_API_ENDPOINT } = process.env;
const search = async (): Promise<any> => {
const res = await fetch(`${REACT_APP_API_ENDPOINT}`);
return (await res.json()).results;
};
useEffect(() => {
(async () => {
const prices = await search();
setPrice(prices);
})();
}, []);
package.json:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
The problem is data is not fetched from the given url, what am I doing wrong here ? Is it because I have created the process.env inside the src folder, or is it because of the DotENV(mikestead) extension that I have installed in my VS-code..
CodePudding user response:
Default path for dot-env package is root folder but if you want to set custom path you can do this with below code.
require('dotenv').config({ path: '/custom/path/to/.env' })
You can refer https://www.npmjs.com/package/dotenv for more information.
CodePudding user response:
The easiest way is to use env-cmd for that
npm i env-cmd
and update your package.json file scripts to look like this:
"scripts": {
"start": "env-cmd -f ./src/process.env react-scripts start"
}