2

I am working on a little project to learn React. It is a movie app listing and its fetching data from themoviedb.org.

I can have a successful call to API and get data I need.

However as it stands I have four listings on landing page and each is a individual component and in each I have separate API call with slightly different parameters.

  const [movies, setMovies] = useState([]);

  useEffect(() => {
    setMovies(API.get("movie/popular"));
  }, [movies]);

Each call will save data with useState() in each component. However it was pointed out to me that this is repetition and that there isnt any API layer to this application.

So, based on that I have created new file called API and in there is a function which fetches data based on passed URL to it.

const API_KEY = "TOP_SECRET_API_KEY"; // 
const BASE_API_URL = "https://api.themoviedb.org/3/"; 

export const API = {
  get: async (url) => {
    const path = BASE_API_URL + url + "?api_key=" + API_KEY;

    const res = await fetch(path);
    const json = await res.json();
    // const { json: json_1, res: res_1 } = { json, res };
    return json;
  },
};

But this is not passing array of results but only Promise. I have tried different approaches via search in google but nothing worked for me.

Could anyone point me into the right direction?

1 Answer 1

2

You need to add await in your useEffect function:

useEffect(() => {
    async function fetchData() {
       const results = await API.get("movie/popular")
       setMovies(results)
    }
    fetchData();
  }, []);
Sign up to request clarification or add additional context in comments.

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.