0

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;

enter image description here

sortinousn
  • 637
  • 2
  • 9
  • 27
  • The dupe question and the first answer it's enough for understanding the problem you're facing. – Ele Dec 18 '19 at 11:08

1 Answers1

1

I'm not sure why since that element exists in the array.

It doesn't … yet.

const [specList, setSpecList] = useState([]);

specList is an empty array.

// Works
console.log(specList[0])

This logs undefined. This is fine.

//Undefined
console.log(specList[0].SpecCode)

You are trying to read the SpecCode property of undefined. This is not fine and throws an exception.

Check that specList[0] has a value before you try to do anything with it.


See also:

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335