简体   繁体   中英

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.

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 Pl.net.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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM