Reputation: 127
I'm using axios.get() to call an api endpoint in one of my components. I need the ability to encapsulate this endpoint call so I can reuse this implementation by calling it from several different components. What is a generally acceptable way to structure this type of implementation in a React project? For example, would it be generally acceptable to group related api calls into js files in a src/services directory at the same level as src/components?
Upvotes: 3
Views: 1471
Reputation: 764
There are many way to do this.
I will recommend to you use hooks. It's more useful and guarantee true way.
3 years ago i lived in Redux
paradigm and every time write the monkey code thinking about consistent Redux
store state.
Please try this one react-async package.
Upvotes: 0
Reputation: 1898
It would be acceptable to create a utils or services directory and group related API calls. However it is important to remember that with async requests you need to consider the components calling the api service utils might un-mount. This might result in warnings or errors if not handled properly. A possible way to handle this might be to only execute callback functions if component is still mounted tracked via a state variable in a useEffect hook.
A more modern react approach might be to leverage hooks and react context for data handling. You could create a DataContext with a useReducer hook to fetch or push data for example. (see https://reactjs.org/docs/context.html)
Upvotes: 1