I’m a beginner in React and would like to call an api and process the result to return it.
But return is empty … whereas "console.log" is ok …
In my index.js :
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import Currencies from './TestApi';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Currencies />
<App />
</React.StrictMode>
);
reportWebVitals();
In my TestApi.js :
import { useState, useEffect } from 'react';
function Currencies() {
const API_URL = 'https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json';
const [options, setOptions] = useState([]);
useEffect(() => {
const fetchOptions = async () => {
try {
const response = await fetch(`${API_URL}`);
const data = await response.json();
let optionsTmp = '';
for (var key in data)
{
optionsTmp = optionsTmp.concat('<option key="').concat(key).concat('">').concat(data[key]).concat('</option> ');
}
setOptions(optionsTmp);
} catch(err) {
console.log(err.message);
}
}
fetchOptions();
}, [options]);
console.log(options);
return (
<select>
{options}
</select>
);
}
export default Currencies;
In my console.log, i’ve got 3 calls (!?) :
console
On my page … :'(
select
>Solution :
You don’t have to create HTML manually in react, use map in JSX like:
function Currencies() {
const API_URL = 'https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json';
const [options, setOptions] = useState({}); // default it as object
useEffect(() => {
const fetchOptions = async () => {
try {
const response = await fetch(API_URL);
const data = await response.json();
setOptions(data);
} catch(err) {
console.log(err.message);
}
}
fetchOptions();
}, [options]);
return (
<select>
{Object.entries(options).map(([key, value]) => (
<option key={key}>${value}</option>
))}
</select>
);
}