Next Server Actions and React Query

In Next 14 server actions allow to avoid creation of the API endpoints. But if you're familiar with the React Query library you should be thinking how could we use this package to interact with Next.js Server Actions.

As you probably know Next.js has built extended version of the fetch method to interact with the API resources. It allows you to call and cache the results from the box. And it s nice.

import { useQuery } from 'react-query'


const useCities = () => {
  return useQuery({
    queryKey: ['useCities'],
    queryFn: async () => {
      return fetch('/api/cities')
    },
  })
}

export default useCities


But what could we do if we don't want to create API endpoints for this. End Server Actions allow us to avoid the creation of the regular API.

The server action can be defined as an asynchronous function with reserved 'use server' directive which can return the response

'use server'

const getAvailableCities = async () => {
  return prismaCall(async (client) => {
    return client.city.findMany({
      include: {
        country: true,
      },
    })
  })
}

export default getAvailableCities

in the given example it returns the list of cities. what if we'll use directly in our hook which is actually wrapper for react-query

import { useQuery } from 'react-query'
import getAvailableCities from 'actions/getAvailableCities'

const useCities = () => {
  return useQuery({
    queryKey: ['useCities'],
    queryFn: async () => {
      return getAvailableCities()
    }
  })
}

export default useCities

and That's all!

Now You can use your server actions call on the 'use client' side without a pain. All known functionality of the react query will remain the same

Enjoy! 🙂