Home > Software design >  How can i fix err for react currency converter?
How can i fix err for react currency converter?

Time:02-15

i've some problems with my currency converter

err: Cannot convert undefined or null to object

const firstCurrency = Object.keys(data.rates)[0];

https://codesandbox.io/s/currency-converter-0b8t7

How can I fix it?

App.js

import React from "react";
import CurrencyConverter from "./components/CurrencyConverter";
import "./styles.css";

export default function App() {
  return (
    <>
      <CurrencyConverter />
    </>
  );
}

CurrencyConverter.js

import React, { useEffect, useState } from "react";
import CurrencyRow from "./CurrencyRow";

const BASE_URL = "https://api.exchangeratesapi.io/latest";

export default function CurrencyConverter() {
  const [currencyOptions, setCurrencyOptions] = useState([]);
  const [fromCurrency, setFromCurrency] = useState();
  const [toCurrency, setToCurrency] = useState();
  const [exchangeRate, setExchangeRate] = useState();
  const [amount, setAmount] = useState(1);
  const [amountInFromCurrency, setAmountInFromCurrency] = useState(true);

  let toAmount, fromAmount;
  if (amountInFromCurrency) {
    fromAmount = amount;
    toAmount = amount * exchangeRate;
  } else {
    toAmount = amount;
    fromAmount = amount / exchangeRate;
  }

  useEffect(() => {
    fetch(BASE_URL)
      .then((res) => res.json())
      .then((data) => {
        const firstCurrency = Object.keys(data.rates)[0];
        setCurrencyOptions([data.base, ...Object.keys(data.rates)]);
        setFromCurrency(data.base);
        setToCurrency(firstCurrency);
        setExchangeRate(data.rates[firstCurrency]);
      });
  }, []);

  useEffect(() => {
    if (fromCurrency != null && toCurrency != null) {
      fetch(`${BASE_URL}?base=${fromCurrency}&symbols=${toCurrency}`)
        .then((res) => res.json())
        .then((data) => setExchangeRate(data.rates[toCurrency]));
    }
  }, [fromCurrency, toCurrency]);

  function handleFromAmountChange(e) {
    setAmount(e.target.value);
    setAmountInFromCurrency(true);
  }

  function handleToAmountChange(e) {
    setAmount(e.target.value);
    setAmountInFromCurrency(false);
  }

  return (
    <>
      <CurrencyRow
        currencyOptions={currencyOptions}
        selectedCurrency={fromCurrency}
        onChangeCurrency={(e) => setFromCurrency(e.target.value)}
        onChangeAmount={handleFromAmountChange}
        amount={fromAmount}
      />
      <CurrencyRow
        currencyOptions={currencyOptions}
        selectedCurrency={toCurrency}
        onChangeCurrency={(e) => setToCurrency(e.target.value)}
        onChangeAmount={handleToAmountChange}
        amount={toAmount}
      />
    </>
  );
}

CurrencyRow.js

import React from "react";

export default function CurrencyRow(props) {
  const {
    currencyOptions,
    selectedCurrency,
    onChangeCurrency,
    onChangeAmount,
    amount
  } = props;

  return (
    <div>
      <select
        className="CurrencyRow"
        value={selectedCurrency}
        onChange={onChangeCurrency}
      >
        {currencyOptions.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
      <input
        type="number"
        className="input"
        value={amount}
        onChange={onChangeAmount}
      />
    </div>
  );
}

CodePudding user response:

As I can see from your codepen, your data is missing a rates property right now. Currently the data object contains the following error 'You have not supplied an API Access Key. [Required format: access_key=YOUR_ACCESS_KEY]' and no rates.

That is why your Object.keys(data.rates)[0]; fails.

To fix it you need to figure out the API key problem, but also to avoid possible errors in the future, I would add a guard to your call. Something like this:

.then((data) => {
        if (!data || !data.rates) return // <-- this here
        const firstCurrency = Object.keys(data.rates)[0];
        setCurrencyOptions([data.base, ...Object.keys(data.rates)]);
        setFromCurrency(data.base);
        setToCurrency(firstCurrency);
        setExchangeRate(data.rates[firstCurrency]);
      });

CodePudding user response:

your fetch request failed with the following respose:

{
  success: false,
  error: {
    code: 101,
    type: "missing_access_key",
    info: "You have not supplied an API Access Key. [Required format: access_key=YOUR_ACCESS_KEY]"
  }
}

as you see there is no rates field in the response

  • Related