TheMayerof
TheMayerof

Reputation: 193

returning information from api call - axios, react hook

I am playing around with an API that returns an object with a TV/Book character's info. I am struggling to get the information I want to load..

I am currently getting the error

TypeError: Cannot read property 'name' of null
const App = () => {

  const url = 'https://www.anapioficeandfire.com/api/characters?name=Jon%20Snow'


  const[count, setCount] = useState(0)
  const[character, setCharacter] = useState(null)

  useEffect(() => {

    async function fetchData() {
      const request = await axios.get(url)
      setCharacter(request.data[0])
      return request
    }
    fetchData()
  }, []);

  return (
    <div className="App">

      {character.name}

    </div>
  );
}

export default App

How can I get the characters name to load?

Upvotes: 0

Views: 34

Answers (1)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

Before the request is complete character is null because that is what you used as initial value. Hence the error. Try

  {character && character.name}

Upvotes: 1

Related Questions