DEV Community

Cover image for Getting Data with Axios
_Khojiakbar_
_Khojiakbar_

Posted on

Getting Data with Axios

The Candy Store Adventure

Imagine you really want some candy. There's a magical candy store in the sky (that's your backend) with all your favorite candies. But instead of going there yourself, you send your pet squirrel, Nutty, to get it for you. And Nutty is super fast—just like Axios!

Step 1: Install Axios

First, you need to give Nutty the ability to fly (install Axios).

npm install axios
Enter fullscreen mode Exit fullscreen mode

Step 2: Send Nutty to the Candy Store

Now, let's send Nutty to the candy store to grab some candies (data). Here's how you can do it in your React component:

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

function CandyStore() {
  const [candies, setCandies] = useState([]); // Empty candy bag

  useEffect(() => {
    // Send Nutty to the candy store
    axios.get('https://example.com/candies')
      .then(response => {
        // Nutty comes back with candies!
        setCandies(response.data);
      })
      .catch(error => {
        // Uh-oh, Nutty got distracted by shiny objects!
        console.error("Nutty couldn't get the candies!", error);
      });
  }, []);

  return (
    <div>
      <h1>My Candy Collection</h1>
      <ul>
        {candies.map(candy => (
          <li key={candy.id}>{candy.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default CandyStore;
Enter fullscreen mode Exit fullscreen mode

Step 3: How It Works (Nutty’s Candy Haul)

  • useState([]): This is your empty candy bag, ready to be filled with delicious treats.

  • useEffect(() => { ... }, []): As soon as you open the candy bag, you tell Nutty to fly off to the candy store (the component mounts).

  • axios.get('https://example.com/candies'): Nutty flies to the candy store to get all the candies.

  • .then(response => { ... }): Nutty comes back with a bag full of candies and drops them in your candy bag (setCandies).

  • .catch(error => { ... }): Oh no! Nutty got distracted by shiny objects and couldn’t find the candy store. You give him a little pep talk.

Step 4: Enjoy the Candy!

Finally, you pour out all the candies Nutty brought back and enjoy them one by one. Each candy is a sweet item in your unordered list (

    ).

What You’ve Learned

  • Axios is like Nutty, your super-fast pet squirrel who fetches data (candies) for you.

  • You can use axios.get() to send Nutty on a candy run.

  • then() is when Nutty comes back with candies, and catch() is when Nutty gets distracted.

Now, you can send Nutty on a candy run (fetch data) anytime you want with Axios in React! 🍬🐿️

Top comments (0)