1

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;

1
  • try it with the entire url given to the axios.get. Does this work? Commented Sep 16, 2020 at 22:55

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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


Comments

0

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();
  }, []);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.