Introduction
When retrieving data using Supabase
.select("*").eq("id", id)
Have you ever encountered an array ([{}]) returned when you only wanted one record?
This is actually a Supabase feature, and by default, it always returns an array.
I had a bit of trouble with this myself at first, so in this article I'll explain why and offer a simple solution.
Example Problem
supabase
.from("study_spots")
.select("*")
.eq("id", id)
.then(({ data }) => console.log(data));
The result is as follows:
[ { id: 1, name: "Cafe A" } ]
➡ The specification is such that even a single result is returned as an array.
In this case, the contents of data are an array, so
you cannot extract the value using data.name.
This is because the data variable itself is an array (similar to a list),
and the object is contained in the first element (the 0th element).
Solution (using .single())
supabase
.from("study_spots") // Specify table
.select("*") // Get all columns
.eq("id", id) // Condition match (id)
.single() // Return only one result
.then(({ data }) => setSpot(data)); // Save to state
This results in this:
{ id: 1, name: "Cafe A" }
Since data is an object,
it can be accessed directly, such as data.name or {spot.name}.
Note: Because Supabase returns SQL results as an "array of rows,"
even a single result will be formatted like [{ ... }].
By adding .single(), it is automatically converted to the { ... } format,
making it easier to handle in React.
Summary
.select() always returns an array.
Adding .single() returns a single object instead of an array.
In React, use .then(({ data }) => setSpot(data)) to save the data to the state and use it.
Top comments (0)