Create ChecheAwtis component

This commit is contained in:
Cédric FAMIBELLE-PRONZOLA
2022-05-21 17:55:16 +04:00
parent b07853998a
commit 5b617236cb
+82
View File
@@ -0,0 +1,82 @@
import {useEffect, useState} from 'react'
import {useRouter} from 'next/router'
import TextField from '@mui/material/TextField'
import Autocomplete from '@mui/material/Autocomplete'
import {Avatar, Container} from '@mui/material'
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.data.map(artiste => {
const firstLetter = artiste.attributes.alias[0].toUpperCase()
return {
firstLetter: /\d/.test(firstLetter) ? '0-9' : firstLetter,
...artiste.attributes
}
})
if (active) {
setOptions([...filteredData])
}
} catch (error) {
console.log('⚠️ Erreur', error.message)
}
})()
return () => {
active = false
}
}, [loading])
return (
<Container sx={{display: 'flex', justifyContent: 'center', marginBlock: 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' />}
onChange={(event, newValue) => {
router.push(`/awtis/${newValue.slug}`)
}}
onOpen={() => {
setOpen(true)
}}
onClose={() => {
setOpen(false)
}}
/>
</Container>
)
}