quintodrome/ui/src/common/useToggleStar.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

44 lines
1.1 KiB
JavaScript
Raw Normal View History

import { useCallback, useEffect, useRef, useState } from 'react'
import { useDataProvider, useNotify } from 'react-admin'
import subsonic from '../subsonic'
export const useToggleStar = (resource, record = {}) => {
const [loading, setLoading] = useState(false)
const notify = useNotify()
const mountedRef = useRef(false)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
}, [])
const dataProvider = useDataProvider()
const refreshRecord = useCallback(() => {
dataProvider.getOne(resource, { id: record.id }).then(() => {
if (mountedRef.current) {
setLoading(false)
}
})
}, [dataProvider, record.id, resource])
const toggleStar = () => {
const toggle = record.starred ? subsonic.unstar : subsonic.star
setLoading(true)
toggle(record.id)
.then(refreshRecord)
.catch((e) => {
console.log('Error toggling star: ', e)
notify('ra.page.error', 'warning')
if (mountedRef.current) {
setLoading(false)
}
})
}
return [toggleStar, loading]
}