Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize an API fetch to be less redundant

I'm building a React App which consumes an API and what I build for now is 2 functions which both GET the same URL but changing the second part of the API Endpoint like URL/?search or URL/?i=123 but what I would like to achieve is to have less redundant code so I was wondering to make one function which just takes the same URL and change the second part of the URL based on the call.

By the way, this approach gives me problems.

The code I did originally was this:

import {API_MOVIE_URL, API_KEY} from "./ApisConst";

export const getMoviesBySearch = async search => {
  try {
    const url = `${API_MOVIE_URL}?apikey=${API_KEY}&${search}`;
    const response = await fetch(url);
    const json = await response.json();
    return json;
  } catch {
    return {
      success: false,
      result: [],
      message: "There is an issue to get data from server. Please try again later.",
    };
  }
};

export const getMoviesInfo = async movieID => {
  try {
    const url = `${API_MOVIE_URL}?apikey=${API_KEY}&i=${movieID}&plot`;
    const response = await fetch(url);
    const json = await response.json();
    return json;
  } catch {
    return {
      success: false,
      result: [],
      message: "There is an issue to get data from server. Please try again later.",
    };
  }
};     

And the change I tried is:

const fetchAPI = async ({type, query}) => {
  const queryParams = {
    byString: `&${query}`,
    byMovieId: `&i=${query}&plot`,
  };

  const endpoint = `${API_MOVIE_URL}?apikey=${API_KEY}${queryParams[type]}`;
  console.log("fetching", endpoint);

  return fetch(endpoint)
    .then(res => res)
    .catch(() => ({
      success: false,
      result: [],
      message: "There is an issue to get data from server. Please try again later.",
    }));
};

export const getMoviesBySearch = async search =>
  await fetchAPI({type: "byString", query: search});

export const getMoviesInfo = async movieID =>
  await fetchAPI({type: "byMovieId", query: movieID});

But this second approach gives me an error in the console which is:

Response {type: "cors", url: "https://www.omdbapi.com/?apikey=API_KEY&s=harry+potter&type=movie", redirected: true, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: true
status: 200
statusText: ""
type: "cors"
url: "https://www.omdbapi.com/?apikey=API_KEY&s=harry+potter&type=movie"

The first approach works perfectly but the second one none and trying to get a solution but cannot really think what to do to get this code better optimized.

like image 285
Jakub Avatar asked Dec 04 '25 16:12

Jakub


1 Answers

Since the queries are identical except for the url, create a query generator (createMoviesQuery) that accepts a function that generates the url (urlGenerator), and returns a query function

Example (not tested):

import {API_MOVIE_URL, API_KEY} from "./ApisConst";

const createMoviesQuery = urlGenerator => async (...params) => {
  try {
    const url = urlGenerator(...params);
    const response = await fetch(url);
    const json = await response.json();
    return json;
  } catch {
    return {
      success: false,
      result: [],
      message: "There is an issue to get data from server. Please try again later.",
    };
  }
};

export const getMoviesBySearch = createMoviesQuery((search) => `${API_MOVIE_URL}?apikey=${API_KEY}&${search}`);

export const getMoviesInfo = createMoviesQuery((movieID) => `${API_MOVIE_URL}?apikey=${API_KEY}&i=${movieID}&plot`);
like image 164
Ori Drori Avatar answered Dec 07 '25 05:12

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!