How to wait until object is fully loaded when fetching with async/await in React

Viewed 1282

I use React for fetching voting objects of a GraphQL API, provided by AWS Amplify. Therefore I created following function that works with async/await:

import { useState, useEffect } from 'react';
import { API } from 'aws-amplify';
import { getVote } from 'src/graphql/queries';

const asGetVoting = (id) => {
  const [vote, setVote] = useState([]);

  const fetchVoting = async () => {
    try {
      const voteData = await API.graphql({
        query: getVote, variables: { id }
      });
      setVote(voteData.data.getVote);
    } catch (error) {
      console.log('Fetching error: ', error);
    }
  };

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

  return vote;
};

export default asGetVoting;

In my component I call the function above and I want to wait until the whole object is fetched - without success:

import asGetVoting from 'src/mixins/asGetVoting';

const Voting = () => {
  const fetchVoting = asGetVoting(id);

  fetchVoting.then((voting) => {
    console.log('Voting completely loaded and ready to do other stuff');
  }).catch((error) => {
    console.log(error);
  });


  return (
    <div>
      some code
    </div>
  );
};

export default Voting;

Any idea what I am doing wrong? Respectively how can I wait until the object is loaded for querying its content? Or is my fetching function (asGetVoting) built in a wrong way? Do I mix async/await stuff with promises?

Thank you for your appreciated feedback in advance.

1 Answers

I think this is a little more complex than it needs to be. If API is returning a promise, you could set your state using .then to ensure the promise has resolved (I didn't included it but should probably add a catch statement as well). Something like:

const asGetVoting = (id) => {
  const [vote, setVote] = useState([]);

  useEffect(() => {
    API.graphql({
      query: getVote, variables: { id }
    }).then(result => setVote(result.data.getVote))
  }, []);

  return (
    // Whatever logic you are using to render vote state
    <div>{vote}</div>
  )

};
Related