robert
robert

Reputation: 83

Using Axios in a React Function

I am trying to pull data from an Axios Get. The backend is working with another page which is a React component.

In a function however, it doesn't work. The length of the array is not three as it is supposed to be and the contents are empty.

I made sure to await for the axios call to finish but I am not sure what is happening.

import React, { useState, useEffect } from "react";

import { Container } from "@material-ui/core";
import ParticlesBg from "particles-bg";
import "../utils/collagestyles.css";
import { ReactPhotoCollage } from "react-photo-collage";
import NavMenu from "./Menu";
import { useRecoilValue } from "recoil";
import { activeDogAtom } from "./atoms";
import axios from "axios";

var setting = {
  width: "300px",
  height: ["250px", "170px"],
  layout: [1, 3],
  photos: [],
  showNumOfRemainingPhotos: true,
};

const Collages = () => {
  var doggies = [];
  //const [dogs, setData] = useState({ dogs: [] });

  const dog = useRecoilValue(activeDogAtom);

  const getPets = async () => {
    try {
      const response = await axios.get("/getpets");
        doggies = response.data;
        //setData(response.data);
    } catch (err) {
      // Handle Error Here
      console.error(err);
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      getPets();
    };
    fetchData();
  }, []);

  return (
    <>
      <NavMenu />
      <ParticlesBg type="circle" margin="20px" bg={true} />
      <br></br>
      <div>
        {doggies.length === 0 ? (
          <div>Loading...</div>
        ) : (
          doggies.map((e, i) => {
            return <div key={i}>{e.name}</div>;
          })
        )}
      </div>
      <Container align="center">
        <p> The length of dogs is {doggies.length} </p>

        <h1>Knight's Kennel</h1>

        <h2> The value of dog is {dog}</h2>
        <h2>
         Breeders of high quality AKC Miniature Schnauzers in Rhode Island
        </h2>
        <section>
          <ReactPhotoCollage {...setting} />
        </section>
      </Container>
    </>
  );
};
export default Collages;

Upvotes: 1

Views: 944

Answers (3)

Lucas Zawadneak
Lucas Zawadneak

Reputation: 26

Try doing the following:

  const [dogs, setData] = useState([]);

  [...]

  const getPets = async () => {
    try {
      const response = await axios.get("/getpets");
        doggies = response.data;
        setData(response.data);
    } catch (err) {
      // Handle Error Here
      console.error(err);
    }
  };

  const fetchData = async () => {
      getPets();
    };

  useEffect(() => {
    fetchData();
  }, []);

No idea if it will actually work, but give it a try if you haven't. If you don't use useState hook to change the array, it won't update on render, so you will only see an empty array on debug.

Upvotes: 1

robert
robert

Reputation: 83

I used setState inside the getPets function. Now it works.

const Collages = () => {
  const [dogs, setData] = useState([]);
  const dog = useRecoilValue(activeDogAtom);

  const getPets = async () => {
    try {
      const response = await axios.get("/getpets");
      setData(response.data);
    } catch (err) {
      // Handle Error Here
      console.error(err);
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      getPets();
    };
    fetchData();
  }, []);

Upvotes: 0

Tadeo Hepperle
Tadeo Hepperle

Reputation: 682

As far as I can tell you do not return anything from the getPets() function.

Make use of the useState Function to save your doggies entries:


let [doggies, setDoggies ] = useState([]);

  const getPets = async () => {
    try {
      const response = await axios.get("/getpets");
        return response.data;
    } catch (err) {
      // Handle Error Here
      console.error(err);
    }
    return []
  };

  useEffect(() => {
    setDoggies(await getPets());
  });


Upvotes: 1

Related Questions