0

I am calling a backend API to get a product in my frontend React application using async/await axios. For this call I defined a function as below:

export const getProduct = ():Promise<Product> => {
  const {data} = await axios.get<Product>('http://myurl.com/api/getproduct');
  return data;
}

Alternatively I can use the code below to return everything returned by get,

export const getProduct = ():Promise<AxiosResponse<Product>> => {
  return axios.get<Product>('http://myurl.com/api/getproduct');
}

I was wondering if there is any best practice recommendation for choosing one over another.

3
  • Why force clients to deal with AxiosResponse? What if you replace axios with Javascript's fetch? Should all clients change as well? Commented Sep 1, 2021 at 7:35
  • I have to use axios as a member of a big team. Commented Sep 1, 2021 at 8:18
  • You don't have to leak it though. Especially in large teams and projects, you don't want the implementation details of one call or module to leak to others. There's no good reason why the caller of getProducts should know anything about how it's loaded. What if you decide to load cache it and load it from session storage? Commented Sep 1, 2021 at 8:19

1 Answer 1

1

I'd advise you to not return everything, normally you implement a class that hides HTTP interface. You can name it service, client or sdk, doesn't matter. But what is the matter you do not expose implementation specifics (like HTTP response) and return only what you need (the data). Especially the name of your function is getProduct, so it is supposed to return a product, not the HTTP response.

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.