Search code examples
node.jssupabase

Supabase returns only 1 row (nodejs)


I'm a Supabase newbie.

I'm getting the whole arrays fine on the first visit of the root '/'

But once I visit the route for 1 specific restaurant '/:id', subsequent visits of '/' will always return only 1 row.

Seems like it's caching it after the '/:id' query.

Please tell me what I'm doing wrong.

Thank you.

no-more-hair-to-pull

const express = require('express')
const router = express.Router()
const supabase = require('../provider/supabase')
const restaurants = supabase.from('restaurants')

router.get('/', async (req, res) => {
  const { data } = await restaurants.select()
  res.json(data)
})

router.get('/:id', async (req, res) => {
  const { id } = req.params
  const { data } = await restaurants.select().eq('id', id)

  if (!data) res.sendStatus(404)

  const restaurant = data.length > 0 ? data[0] : undefined

  if (!restaurant) {
    res.sendStatus(404)
    
  }
  res.json(restaurant)
})

Solution

  • Because how the client Supabase client library is structured, you currently cannot keep supabase.from('restaurants') as a variable. This will remember the old query that was used against it. The solution here is to always call from() whenever you want to construct a new query.

    const express = require('express')
    const router = express.Router()
    const supabase = require('../provider/supabase')
    
    router.get('/', async (req, res) => {
      const { data } = await supabase.from('restaurants').select()
      res.json(data)
    })
    
    router.get('/:id', async (req, res) => {
      const { id } = req.params
      const { data } = await supabase.from('restaurants').select().eq('id', id)
    
      if (!data) res.sendStatus(404)
    
      const restaurant = data.length > 0 ? data[0] : undefined
    
      if (!restaurant) {
        res.sendStatus(404)
        
      }
      res.json(restaurant)
    })