Skip to content

Instantly share code, notes, and snippets.

@dhbalaji
Last active April 16, 2020 17:17
Show Gist options
  • Save dhbalaji/df01d2fcbbbad74a283b4ed71f50ce8e to your computer and use it in GitHub Desktop.
Save dhbalaji/df01d2fcbbbad74a283b4ed71f50ce8e to your computer and use it in GitHub Desktop.
Right way to do Ajax Call in React Hooks

React hooks Ajax Call - the right way

React hooks are used in functional components. It means, we no longer have componentWillMount or componentDidMount. Lets find out how to do ajax call in React hook useEffect.

const [animals, setAnimals] = React.useState([]);

React.useEffect(() => {
    const fetchAnimals = async () => {
        const response = await axios.get(`https://api.github.com/animals/`);
        setAnimals(response.data);
    }

    fetchAnimals();
  }, []); // This will be triggered only once.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment