Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does axios need extra config to get data from REST API?

I am trying to convert the fetch API to axios with get method.
Prior to do this, I plan to keep using ‘async, await’.

And when I replaced the code below:

// before
const fetchPlanets = async () => {
  const res = await fetch("http://swapi.dev/api/planets/");
  return res.json();
};

// after
const fetchPlanets = async () => {
  const res = await axios
    .get("http://swapi.dev/api/planets/")
    .then((respond) => {
      respond.data;
    });
};
  • async can be used when to address the function.
  • and returned const res as res.json();
  • Also…axios does not require to res.json as it returned as json type.

That’s how I understand this so far. And with fetch API, this work flawlessly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How the code should be to let axios work as I expected?

// Planets.js
import React from "react";
import { useQuery } from "react-query";
import Planet from "./Planet";
// import axios from "axios";

const fetchPlanets = async () => {
  const res = await fetch("http://swapi.dev/api/planets/");
  return res.json();
};

const Planets = () => {
  const { data, status } = useQuery("planets", fetchPlanets);
  console.log(data);

  return (
    <div>
      <h2>Planets</h2>

      {status === "loading" && <div>Loading data...</div>}

      {status === "error" && <div>Error fetching data!</div>}

      {status === "success" && (
        <div>
          {data.results.map((planet) => (
            <Planet key={planet.name} planet={planet} />
          ))}
        </div>
      )}
    </div>
  );
};

export default Planets;

And Planet.js; just in case.

import React from "react";

const Planet = ({ planet }) => {
  return (
    <div className="card">
      <h3>{planet.name}</h3>
      <p>Population - {planet.population}</p>
      <p>Terrain - {planet.terrain}</p>
    </div>
  );
};

export default Planet;

>Solution :

There are 2 problems in your axios code.

  1. You should return respond.data.

  2. You should return the whole axios response.

So this would work:

const fetchPlanets = async () => {
  return await axios
    .get("http://swapi.dev/api/planets/")
    .then((respond) => {
      return respond.data;
    });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading