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

Time:12-01

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.

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;

CodePudding user response:

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;
    });
};
  • Related