Insert parameter in template literal for fetch URI in React useEffect

80 views Asked by At

Utilizing .then with fetch uri insertion of '...${currency}.json' parameter runs correctly w/ no error:

useEffect(() => {
   fetch(`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${currency}.json`)
      .then((res) => res.json())
      .then((res) => setData(res[currency]))
}, [currency])

Utilizing async await with fetch uri insertion of '...${currency}.json' parameter gives a syntax error at parameter insertion'...${currency}.json':

const useCurrencyInfo2 = (currency) => {
   const [data, setData] = useState({});
   const [isError, setIsError] = useState(false);

   useEffect(() => {
      const fetchCurrency = async () => {
         try {
            const resp = await fetch(`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${currency}.json`)

            if (!resp.ok) {
               setIsError(true)
               return
            }
            const json = await resp.json()
            setData(json[currency])

         } catch (error) {
            setIsError(true)
         }
      }
      fetchCurrency();
   }, [currency])
  
   return data
}
1

There are 1 answers

5
OlegWock On

In your second snippet, inside the effect you define variable currency, which shadows original currency from hook parameters.

const currency = await resp.json()

Now, browser, when executing fetch knows that there will be variable currency in current scope, but it's not defined yet. So it throws an error when you try not-yet defined variable. To fix this you'll need to use different variable name for response's json:

const json = await resp.json()
setData(json[currency])