import React, { Suspense } from 'react'; import styled from 'styled-components'; import { useRecoilValue } from 'recoil'; import { useEffect } from 'react'; import { useCallback } from 'react'; import { useState } from 'react'; import { useParams } from 'react-router-dom'; import { screen } from '../../styles/screen'; import { categoriesQuery } from '../../recoil/categories/categories'; import withSuspense from '../../hooks/withSuspense'; const Wrapper = styled.div` margin-bottom: 10px; `; const Image = styled.div<{ url: string }>` background-image: url(${({ url }) => url}); background-size: cover; background-repeat: no-repeat; min-height: 200px; transition: background-image 0.75s ease-in-out; width: 100%; ${screen.md} { min-height: 400px; } `; const Title = styled.h1` font-size: 1.5rem; margin-bottom: 1rem; color: #3e4457; letter-spacing: 10px; text-transform: uppercase; ${screen.md} { letter-spacing: 15px; } `; const getByName = (categories: Category[], categoryName: string) => { return ( categories.find(({ name }) => name === categoryName) || categories[0] ); }; function Banner() { const { categoryName } = useParams<{ categoryName: string }>(); const categories = useRecoilValue(categoriesQuery); const [category, setCategory] = useState( getByName(categories, categoryName) ); const getRandomCategory = useCallback(() => { return categories[Math.floor(Math.random() * categories.length)]; }, [categories]); useEffect(() => { if (!categoryName) { const handle = setInterval( () => setCategory(getRandomCategory()), 4000 ); return () => clearInterval(handle); } }, [categoryName, setCategory, getRandomCategory]); useEffect(() => { setCategory(getByName(categories, categoryName)); }, [categories, categoryName]); return ( Loading}> {category.label} ); } export default withSuspense(Banner,
Carregando
);