I use useQuery() to receive data from the server. In order not to repeat the API site address and a series of additional parameters each time, I used the following custom hook:
export function useGetApi(mode, params, key) {
// get initial config from context:
const { config } = useGetConfig();
const url = `https://example.com/api/${ mode }/?${ params }&lang_code=${ config.language }`;
const queryKey = `${key}_${config.language}`;
// async function for get API:
async function getApi() {
const { data } = await axios.get(url);
return data;
}
return useQuery(['getApi', queryKey], getApi, {
enabled: !!config.language
});
}
A series of basic settings, including language, are located in a context called "Config". In every component and every need I have, I call this custom hook and fill in the arguments, for example:
const { isLoading, data: products } = useGetApi(`products`, `company_id=${companyId}`, `products_${companyId}`);
Is this wrong?