Get the Bill: making HTTP requests to the API

hello everyone,here is my code,what am i doing wrong…its not executing

  const
			amountNew=amount.toLocaleString(en-${country.code},
			{style:"currency",
			       currency:country.currency||'USD'});
			                                      return
								amountNew;
	  };
	        
	 const detectCardType = (first4Digits) =>{}
	 const validateCardExpiryDate = () => {}
	 const validateCardHolderName = () => {}
	 const uiCanInteract = () => {}
	 const displayCartTotal = ({results}) => {
                         let[data]=results
						 let{buyerCountry,itemsInCart}=data;
						                  const initial=0;
				appState.items=itemsInCart;
				appState.country=buyerCountry;
				appState.bill=itemsInCart.reduce((acc,val)=>{
					                                     return
						         acc+(val['price']*val['qty']);
				                      },initial);
		appState.billFormatted=formatAsMoney(appState.bill,appState.country);	
		document.querySelector('[data-bill]').textContent=appState.billFormatted;
		appState.cardDigits = [];
		appState.cardDigits = [0];
		appState.cardDigits = [1];
		appState.cardDigits = [2];
		appState.cardDigits = [3];
		uiCanInteract();

	   };
      const startApp = () => {
		  fetchBill();
      };

Hi, please, can you change title and section of your topic appropriately?
Can you tell us also more about the problem you are experiencing? At the moment I only see a bunch of empty arrow functions but I don’t know what you are trying to achieve. I understood that you want to destructure but I don’t see objects or array that can be destructured…

  • Within the SCRIPT element and just after the billHype function, create an appState variable and assign it an empty Object literal. This variable will hold data for the app.
  • Create a formatAsMoney function. It should take in an amount and a buyerCountry parameter. It will use these parameters to format the user’s bill as a proper currency.
  • Create detectCardType , validateCardExpiryDate , and validateCardHolderName functions. detectCardType should be declared to accept first4Digits as a parameter represneting the first four digits of the 16-digit long credit card number. As implied by their names, these functions will play major roles in validating various aspects of the card being used for payment
  • Create a uiCanInteract function. It will be called to setup the UI, including adding event handlers to enable interactions with the app.
  • Create a displayCartTotal function. It should expect a parameter and should use object de-structuring to obtain the results property of the given parameter. This function will be called with the data from an API call and it will display the total bill to be paid.

Step 2

  • Update the fetchBill function. It should then use the browser’s fetch function to make a HTTP request to apiEndpoint . Using an arrow function in a .then call to the fetch function, return the response after converting it to JSON. Using another .then call to the first one, pass the JSON data to displayCartTotal . Make sure to handle errors that may occur, e.g by showing a warning message in the console.
  • Call the fetchBill function from inside the startApp . This should be the only code or function call within startApp .

Step 3

  • In the body of the displayCartTotal function, de-structure the first item in the results array parameter into a data variable. Next, use object de-structuring to obtain the itemsInCart and buyerCountry properties from data . You might want to install the JSONViewer Chrome extension, open a new tab and navigate to https://randomapi.com/api/006b08a801d82d0c9824dcfdfdfa3b3c to see the shape of the JSON data we are dealing with.
  • Next, displayCartTotal should set appState.items to itemsInCart and appState.country to buyerCountry .
  • Use the Array .reduce function to calculate the total bill from itemsInCart Note that each item has a qty property indicating how many of that item the user bought. Assign the calculated bill to appState.bill
  • Go back to the formatAsMoney function. Use the in-built javascript .toLocaleString function on the amount and buyerCountry parameters to format amount as a currency with the currency symbol of buyerCountry . The countries and their currency symbols are in the countries array you got in your starter code. If the buyerCountry is not in countries , then use United States as the country and format the currency accordingly.
  • Continuing from where you left off in displayCartTotal , use the formatAsMoney function to set appState.billFormatted to the formatted total bill. The already assigned appState.bill and appState.country should be handy for this task!
  • Set the text content of the data-bill SPAN element to the formatted bill saved in appState.billFormatted
  • Assign an array literal to appState.cardDigits
  • Finally, call uiCanInteract to wrap up displayCartTotal

Firstly, welcome to the forums.

While we are primarily here to help people with their Free Code Camp progress, we are open to people on other paths, too. Some of what you are asking is pretty trivial in the Free Code Camp context, so you might find that if you’re not getting the instruction and material you need in your current studies, the FCC curriculum will really help you get started. At a modest guess I’d say investing a 4-5 hours working through the curriculum here will really pay off. You can find the curriculum at https://learn.freecodecamp.org.

With your current questions, we don’t have enough context to know what you already know or don’t know, so it is impossible to guide you without just telling you the answer (which we won’t do).

It is pretty typical on here for people to share a codepen / jsfiddle example of what they have tried so that anyone helping has more of an idea of what help is actually helpful.

Please provide some example of what you’ve tried and I’m sure you’ll get more help.

Happy coding :slight_smile:

i too am experiencing a chellenge,here is my code…where am i going wrong?experiencing syntax errors…

  const
			amountNew=amount.toLocaleString(en-${country.code},
			{style:"currency",
			       currency:country.currency||'USD'});
			                                      return
								amountNew;
	  };
	        
	 const detectCardType = (first4Digits) =>{}
	 const validateCardExpiryDate = () => {}
	 const validateCardHolderName = () => {}
	 const uiCanInteract = () => {}
	 const displayCartTotal = ({results}) => {
                         let[data]=results
						 let{buyerCountry,itemsInCart}=data;
						                  const initial=0;
				appState.items=itemsInCart;
				appState.country=buyerCountry;
				appState.bill=itemsInCart.reduce((acc,val)=>{
					                                     return
						         acc+(val['price']*val['qty']);
				                      },initial);
		appState.billFormatted=formatAsMoney(appState.bill,appState.country);	
		document.querySelector('[data-bill]').textContent=appState.billFormatted;
		appState.cardDigits = [];
		appState.cardDigits = [0];
		appState.cardDigits = [1];
		appState.cardDigits = [2];
		appState.cardDigits = [3];
		uiCanInteract();

	   };
      const startApp = () => {
		  fetchBill();
      };

try this….appstate.bill = itemsIncart.reduce((acc,val)=>{acc+(val.price*val.qty)},0);

and then just use appState.cardDigits = [ ]; only,remove the rest

Kindly post your code

`const displayCartTotal = ({results}) =>{
const [data] = results;
const{itemsInCart,buyerCountry}=data;
appState.items = itemsInCart;
appState.country = buyerCountry;
appState.bill = itemsInCart.reduce((result,item)=>{
result+(item.price*item.qty)
},0);
appState.billFormatted = formatAsMoney(appState.bill,appState.country);
const billSpan = document.querySelector(’[data-bill]’);

billSpan.textContent = appState.billFormatted;
	  appState.cardDigits=[];
	  uiCanInteract();`
<title>Mini App</title>

<style>
	body {
		margin: 0;
		padding: 1em;
		background-color: #fff;
	}


	[data-cart-info],
	[data-credit-card] {
		transform: scale(0.78);
		margin-left: -3.4em;
	}

	[data-cc-info] input:focus,
	[data-cc-digits] input:focus {
		outline: none;
	}

	.mdc-card__primary-action,
	.mdc-card__primary-action:hover {
		cursor: auto;
		padding: 20px;
		min-height: inherit;
	}

	[data-credit-card] [data-card-type] {
		transition: width 1.5s;
		margin-left: calc(100% - 130px);
	}

	[data-credit-card].is-visa {
		background: linear-gradient(135deg, #622774 0%, #c53364 100%);
	}

	[data-credit-card].is-mastercard {
		background: linear-gradient(135deg, #65799b 0%, #5e2563 100%);
	}

	.is-visa [data-card-type],
	.is-mastercard [data-card-type] {
		width: auto;
	}

	input.is-invalid,
	.is-invalid input {
		text-decoration: line-through;
	}

	::placeholder {
		color: #fff;
	}

	/* Add Your Css From Here*/
	span {
		display: inline-block;
		vertical-align: middle;
	}

	[data-credit-card] {
		width: 435px;
		min-height: 240px;
		background-color: #5d6874;
		border-radius: 10px;
	}

	span.material-icons {
		font-size: 150px;
	}

	[data-card-type] {
		display: block;
		width: 120px;
		height: 60px;
	}

	[data-cc-digits] {
		margin-top: 2em;
	}

	[data-cc-digits]>input {
		color: #ffffff;
		background: none;
		font-size: 2em;
		line-height: 2em;
		border: none;
		margin-right: 0.5em;
	}

	[data-cc-info] {
		margin-top: 1em;
	}

	[data-cc-info]>input {
		color: #ffffff;
		font-size: 1.2em;
		border: none;
		background: none;
	}

	[data-cc-info]>input:nth-child(2) {
		padding-right: 10px;
		float: right;
	}

	[data-pay-btn] {
		position: fixed;
		border: 1px solid;
		width: 90%;
		bottom: 20px;
	}
</style>
<!-- your HTML goes here -->
<div data-cart-info>
	<heading class="mdc-typography--headline4">
		<span class="material-icons">
			shopping_cart
			</span>
		<span data-bill>

		</span>
	</heading>
</div>
<div data-credit-card class="mdc-card mdc-card--outlined">
	<div class="mdc-card__primary-action">
		<img src="https://placehold.it/120x60.png?text=Card" data-card-type>
		<div data-cc-digits>
			<input type="text" size="4" placeholder="----"/>
			<input type="text" size="4" placeholder="----"/>
			<input type="text" size="4" placeholder="----"/>
			<input type="text" size="4" placeholder="----"/>
		</div>
			<div data-cc-info>
				<input type="text" size="20" placeholder="Name Surname"/>
				<input type="text" size="6" placeholder="MM/YY"/>
		</div>
			</div>

		</div>
		<button class="mdc-button" data-pay-btn>
	Pay Now
</button>
		<script>
			const supportedCards = {
    visa, mastercard
  };

  const countries = [
    {
      code: "US",
      currency: "USD",
      currencyName: '',
      country: 'United States'
    },
    {
      code: "NG",
      currency: "NGN",
      currencyName: '',
      country: 'Nigeria'
    },
    {
      code: 'KE',
      currency: 'KES',
      currencyName: '',
      country: 'Kenya'
    },
    {
      code: 'UG',
      currency: 'UGX',
      currencyName: '',
      country: 'Uganda'
    },
    {
      code: 'RW',
      currency: 'RWF',
      currencyName: '',
      country: 'Rwanda'
    },
    {
      code: 'TZ',
      currency: 'TZS',
      currencyName: '',
      country: 'Tanzania'
    },
    {
      code: 'ZA',
      currency: 'ZAR',
      currencyName: '',
      country: 'South Africa'
    },
    {
      code: 'CM',
      currency: 'XAF',
      currencyName: '',
      country: 'Cameroon'
    },
    {
      code: 'GH',
      currency: 'GHS',
      currencyName: '',
      country: 'Ghana'
    }
  ];

  const billHype = () => {
    const billDisplay = document.querySelector('.mdc-typography--headline4');
    if (!billDisplay) return;

    billDisplay.addEventListener('click', () => {
      const billSpan = document.querySelector("[data-bill]");
      if (billSpan &&
        appState.bill &&
        appState.billFormatted &&
        appState.billFormatted === billSpan.textContent) {
        window.speechSynthesis.speak(
          new SpeechSynthesisUtterance(appState.billFormatted)
        );
      }
    });
  };

  const appState = {};
  const formatAsMoney = (amount,buyerCountry)=>{

const ountry = countries.find((x)=>x.country === buyerCountry) || countries[0];
return amount.toLocaleString(en-${country.code},{
style:“currency”,
currency:country.currency
});

  }
  		
  const detectCardType =(first4Digits)=>{}
  const validateCardExpiryDate = () =>{}
  const validateCardHolderName = () =>{}




  const uiCanInteract = () =>{}
  const displayCartTotal = ({results}) =>{
	  const [data] = results;
	  const{itemsInCart,buyerCountry}=data;
	  appState.items = itemsInCart;
	  appState.country = buyerCountry;
	  appState.bill = itemsInCart.reduce((result,item)=>{
		  result+(item.price*item.qty)
	  },0);
	  appState.billFormatted = formatAsMoney(appState.bill,appState.country);
const billSpan = document.querySelector('[data-bill]');
billSpan.textContent = appState.billFormatted;
	  appState.cardDigits=[];
	  uiCanInteract();
	  
  };	  

  
  const fetchBill = () => {
    const api = 'https://randomapi.com/api/006b08a801d82d0c9824dcfdfdfa3b3c';
	fetch(api)
	.then(responce=>response.json())
	.then(response=>data(displayCartTotal))
	.catch(error=>console.error('Error :',error));
	const apiKey = '006b08a801d82d0c9824dcfdfdfa3b3c';
	const apiEndpoint = `${apiHost}/${apiKey}`;
	
    
  };
  
  const startApp = () => {
	  fetchBill();
  };

  startApp();
		</script>

that’s the point i have reached

kindly assist…“expected an assignment or function call”…cant seem to get it right

const appState = {}
const formatAsMoney = (amount, buyerCountry) => {}
const country = countries.find(country => {
  return
  country.country === buyerCountry
}) || countries.find(country => {
  return
  country.country === "United States";
  const amountNew = amount.toLocaleString(en - $(country.code), {
    style: "currency",
    currency: country.currency || USD
  });
  return
  amountNew;
})

Use this

const formatAsMoney = (amount, buyerCountry) => {
  let country = countries.find(({ country }) => country === buyerCountry) || {
    code: 'US',
    currency: 'USD'
  }
  return amount.toLocaleString(country.code, {
    style: 'currency',
    currency: country.currency
  })
}