@@ -35,37 +35,39 @@ const displayCarbonUsage = async (apiKey, region) => {
3535 try {
3636 await axios
3737 . get ( 'https://api.co2signal.com/v1/latest' , {
38- params : {
39- countryCode : region ,
40- } ,
41- headers : {
42- //please get your own token from CO2Signal https://www.co2signal.com/
43- 'auth-token' : apiKey ,
44- } ,
38+ params : { countryCode : region } ,
39+ headers : { 'auth-token' : apiKey } ,
4540 } )
4641 . then ( ( response ) => {
47- let CO2 = Math . floor ( response . data . data . carbonIntensity ) ;
42+ const data = response ? .data ? .data ;
4843
44+ // ✅ Validate required data before using
45+ if ( data ?. carbonIntensity == null || data ?. fossilFuelPercentage == null ) {
46+ throw new Error ( 'Missing carbon intensity or fossil fuel data' ) ;
47+ }
48+
49+ let CO2 = Math . floor ( data . carbonIntensity ) ;
4950 calculateColor ( CO2 ) ;
5051
5152 loading . style . display = 'none' ;
5253 form . style . display = 'none' ;
5354 myregion . textContent = region ;
5455 usage . textContent =
55- Math . round ( response . data . data . carbonIntensity ) + ' grams (grams C02 emitted per kilowatt hour)' ;
56+ Math . round ( data . carbonIntensity ) + ' grams (grams C02 emitted per kilowatt hour)' ;
5657 fossilfuel . textContent =
57- response . data . data . fossilFuelPercentage . toFixed ( 2 ) +
58+ data . fossilFuelPercentage . toFixed ( 2 ) +
5859 '% (percentage of fossil fuels used to generate electricity)' ;
5960 results . style . display = 'block' ;
6061 } ) ;
6162 } catch ( error ) {
62- console . log ( error ) ;
63+ console . warn ( 'Data fetch failed:' , error . message ) ;
6364 loading . style . display = 'none' ;
6465 results . style . display = 'none' ;
65- errors . textContent = 'Sorry, we have no data for the region you have requested .' ;
66+ errors . textContent = 'Sorry, data unavailable for the selected region .' ;
6667 }
6768} ;
6869
70+
6971// set up api key and region
7072const setUpUser = async ( apiKey , region ) => {
7173 localStorage . setItem ( 'apiKey' , apiKey ) ;
0 commit comments