I'm new player with React, Next and Supabase with realtime and I don't understand why I encountered an issue.
In the simplified example below, I'm displaying a user list with data from Supabase.
I subscribe to the users table for listening realtime changes in useEffect hook and return the unsubscribe function to clean up.
When I'm using Paginator to setPage and fetchData everything is OK, but when I receive updates from subscribe, fetchData is always executed with page in its initial state (page = 0), not current state.
The simplified example used:
export default function Index() {
const [users, setUsers] = useState([])
const [page, setPage] = useState(0)
const fetchData = async () => {
const { data } = await supabaseClient
.from<User>('users')
.select('id, email')
.range(page * 10, page * 10 + 10 - 1)
setUsers(data)
}
useEffect(() => {
fetchData()
const usersSubscription = supabaseClient
.from<User>('users')
.on('*', fetchData)
.subscribe()
async function removeSubscription() {
await supabaseClient.removeSubscription(usersSubscription)
}
return () => {
removeSubscription()
}
}, [])
return (
<UserList users={users}/>
<Paginator page={page} .../>
)
}
I think I'm violating the rules of hooks. Any ideas ?