I'm trying to access an element from an API that returns an array data from a submit function. I can access the entire object but when trying to access a specific element like specCode
in the object I get an undefined error. I'm not sure why since that element exists in the array.
function App() {
const [searchText, setSearchText] = useState("");
const [specList, setSpecList] = useState([]);
const handleSubmit = event => {
event.preventDefault();
fetch("https://fishbase.ropensci.org/comnames?Comname=" + searchText)
.then(response => response.json())
.then(({ data }) => {
setSpecList(data);
});
// Works
console.log(specList[0])
//Undefined
console.log(specList[0].SpecCode)
};
return (
<form onSubmit={handleSubmit}>
<input
class="form-control mr-1"
type="text"
placeholder="Large input"
type="text"
placeholder="Search for Fish by Name"
value={searchText}
onChange={event => setSearchText(event.target.value)}
/>
<button type="submit" class="btn btn-primary">
enter
</button>
</form>
);
}
export default App;