Quick start
Through the next few examples we will teach you have to fetch data from Punk API (opens in a new tab). This is a JSON based REST API. You will get familiar with all the basic concepts so you can take it away working on your own project.
Project setup
The following steps will explain you in depth how to setup Data Service in your project. If you are already familiar with the process you can skip to the next section.
Install
First you need to install the library. You can do that by running the following command in your terminal via your package manager of choice.
npm install @kickass-coderz/data-service @tanstack/react-query
We build our data hooks on top of industry accepted React Query (opens in a new tab). So we also install it as a peer dependency.
Creating a DataService
To start consuming data service you first have to create a DataService instance. which will actually make underlying API calls. You can create your own by implementing our IDataService
interface or by using one of our premade classes.
We provide RestDataService
following data services as part of the library.
To implement your own DataService you can check out the following example or you can use existing DataServices from this list.
Let's continue with RestDataService for this example 😄.
import type { AppProps } from 'next/app'
import {useState} from "react"
import { RestDataService } from '@kickass-coderz/data-service'
const App = ({ Component, pageProps }: AppProps) => {
const [dataService] = useState(() => new RestDataService('https://api.punkapi.com/v2'))
return <Component {...pageProps} />
}
export default App
Adding a DataServiceProvider to your app
Now that you have your DataService ready you need to hook it up inside your app. Best place for that is inside the root file of your application. We will also use our RestDataService
for the examples. As mentioned before we will be fetching some beers from Punk API (opens in a new tab).
Lets implement it:
import type { AppProps } from 'next/app'
import {useState} from "react"
import { RestDataService, DataServiceProvider } from '@kickass-coderz/data-service'
const App = ({ Component, pageProps }: AppProps) => {
const [dataService] = useState(() => new RestDataService('https://api.punkapi.com/v2'))
return (
<DataServiceProvider dataService={dataService} >
<Component {...pageProps}/>
</DataServiceProvider>
)
}
export default App
Good to go! 🎉
Great 😄, that was a breeze! With our project setup complete, we can start using our premade hooks to fetch and use data inside our components 💪.
Fetching data
We provide the hooks that match IDataService
interface. So for example if you wish to fetch a list of items from your API you would use useGetList
hook that will call DataService.getList
method under the hood.
import { useGetList } from '@kickass-coderz/data-service'
const Component = () => {
const { data, isLoading } = useGetList({
resource: 'beers' // this calls https://api.punkapi.com/v2/beers
})
if (isLoading) {
// show loading indicator until data is loaded
// data will be undefined until fetched for the first time
return <div>Loading</div>
}
return (
<ul>
{data.map(item => {
return <li>{item.name}</li>
})}
</ul>
)
}
To fetch data for single beer we just need useGetOne
hook that will call DataService.getOne
method under the hood.
const { data, isLoading } = useGetOne({
resource: 'beers',
params: {
id: 1 // this calls https://api.punkapi.com/v2/beers/1
}
})
We also provide hook for other REST methods and CRUD actions:
- useCreateOne (and useCreateMany)
- useUpdateOne (and useUpdateMany)
- useDeleteOne (and useDeleteMany)
The methods ending with Many
are special methods that can get, create, update or delete multiple records in the same time. You can read more in our Fetching multiple resources guide.
Error handling
If any kind of error occurs during data fetching you will get it through error
property.
const { error, isError } = useGetOne({
resource: 'beers',
params: {
id: 1 // this calls https://api.punkapi.com/v2/beers/1
}
})
if (isError) {
return <ErrorMessage error={error}>
}
You can also detect if the hook is in error state with isError
property.
Bonus features
Remember that we handle caching, background updates, retries and stale data out of the box with zero-configuration. In case you don't know what that means or are interested in more details you can find concrete examples below.
Caching
All of the data you fetch from your API is automatically cached on the client side. Which means that if you fetch some data from your API in component A and call the same hook inside component B, there will be no additional network call. The component B will just reuse the cached data. If you wish to know more check out our Caching topic.
Background updates and stale data
If any of the data becomes stale (cache is no longer valid) our hooks will automatically fetch the data again. If multiple instaces of the same hook are active there will be only one network call and other hooks will just reuse the newly fetched data.
Automatic retrys
If any of the calls to your API fail for some reason (promise gets rejected) our hooks will automatically retry for a chance to get the data. If that fails multiple times you will get an error
object which you can then use to show error state inside your app. You can find more about this from our DataClient page.