I have simple API that my React App can use to communicate with my backend. The API has different endpoints and 3 different versions and works like this:
- We have the public URL, that anonymous users can use (public.api.mysite.com)
- We have the private URL, that only signed in users can use with their credentials(private.api.mysite.com)
- Some endpoints on the private API may simply point to the same code which would just ignore the credentials
- theres also a API URL for testing, which most of the time runs on localhost
I was thinking of creating a REACT component that is used for handling all API communication that might look like this:
<APIConsumer
url="posts/7daa4649-14bd-4521-83a3-87609da277d9" method="post"
payload={data}
handleError={(e)=>setLabel("Error occured because "+e.message)}
handleLoading={()=>setLabel("Loading please wait")}
handleSuccess={
(data)=>{
setLabel(null);
setPosts((oldPosts)=>[...oldPosts,data])
}
}
/>
The advantage with this is I can just change the backend URL in one place if the user logs in or during development. I can also create a user context with user credentials which can be consumed within APIConsumer.
But it also feels like an antipattern, since it handles state changes at the lower component (APIConsumer instead of its parent component).
Theres also the fact that I never saw a pattern like this in the wild. I usually see a large chunk of code handling interaction with the api using fetch or axios at the top level component (including all post, get, patch, etc.. operations).
So is this approach to generalizing api communication a good idea or is it an antipattern?