Files
pawol.nu/components/awtis/cheche-awtis.js
T

104 lines
2.8 KiB
JavaScript

'use client'
import {useEffect, useState} from 'react'
import {useRouter} from 'next/navigation'
import TextField from '@mui/material/TextField'
import Autocomplete from '@mui/material/Autocomplete'
import Avatar from '@mui/material/Avatar'
import CircularProgress from '@mui/material/CircularProgress'
import Container from '@mui/material/Container'
import {jwennToutAwtis} from '../../lib/oki-api'
const IMAGE_URL = process.env.NEXT_PUBLIC_API_URL_ROOT || 'http://localhost:1337'
export default function ChecheAwtis() {
const router = useRouter()
const [open, setOpen] = useState(false)
const [options, setOptions] = useState([])
const loading = open && options.length === 0
useEffect(() => {
let active = true
if (!loading) {
return undefined
}
(async () => {
try {
const {data} = await jwennToutAwtis()
const filteredData = data.map(artiste => {
const firstLetter = artiste.alias[0].toUpperCase()
return {
firstLetter: /\d/.test(firstLetter) ? '0-9' : firstLetter,
...artiste
}
})
if (active) {
setOptions([...filteredData])
}
} catch (error) {
console.log('⚠️ Erreur', error.message)
}
})()
return () => {
active = false
}
}, [loading])
return (
<Container
sx={{ display: 'flex', justifyContent: 'center', marginBottom: 3 }}
>
<Autocomplete
autoHighlight
disableClearable
disableCloseOnSelect
loading={loading}
open={open}
loadingText='Chargement...'
noOptionsText='Aucun résultat'
id='cheche-awtis'
options={options.sort((a, b) => -b.firstLetter.localeCompare(a.firstLetter))}
groupBy={option => option?.firstLetter}
getOptionLabel={option => option?.alias}
renderOption={(props, option) => (
<li {...props}>
<Avatar style={{marginRight: 8}} alt={option?.alias} src={`${IMAGE_URL}${option?.photo?.data?.attributes?.formats?.thumbnail?.url}`} />
{option?.alias}
</li>
)}
sx={{width: 300}}
renderInput={params => (
<TextField
{...params}
label='Rechercher un artiste'
InputProps={{
...params.InputProps,
endAdornment: (
<>
{loading ? <CircularProgress color='primary' size={20} /> : null}
{params.InputProps.endAdornment}
</>
),
}}
/>
)}
onChange={(event, newValue) => {
router.push(`/awtis/${newValue.slug}`)
}}
onOpen={() => {
setOpen(true)
}}
onClose={() => {
setOpen(false)
}}
/>
</Container>
)
}