Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

react : calling APIs after render w error message

import { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [imageUrl, setImageUrl] = useState('https://images.dog.ceo/breeds/hound-afghan/n02088094_1003.jpg');
  const [errorMessage, setErrorMessage] = useState('');

  useEffect(() => {
    axios.get('https://dog.ceo/api/breeds/image/random')
      .then((response) => {
        setImageUrl(response.data.message);
      })
      .catch((error) => {
        setErrorMessage(<section>{error.response.data.message}</section>);
      });
  }, []);

  return (
    <div>
      <h1>My Dog Log</h1>
      {errorMessage}
      <div>
        <img src={imageUrl} alt="A random dog" />
      </div>
    </div>
  );
}
Source by learn-2.galvanize.com #
 
PREVIOUS NEXT
Tagged: #react #calling #APIs #render #error #message
ADD COMMENT
Topic
Name
1+1 =