import { ChangeEvent, FormEvent, useEffect, useState } from 'react'; import { ASAllInput, ASButton, ASForm, ASText } from 'components'; import { useApi } from 'utils'; import './index.scss'; import { FactsApi } from './api'; export function Facts() { const [factQuery, setFactQuery] = useState(''); const [factQueryError, setFactQueryError] = useState(''); const [fact, setFact] = useState(''); const { fetch: fetchRandomFacts } = useApi(FactsApi.getRandomFact); const { fetch: fetchSearchResult } = useApi(FactsApi.fetchSearchResult); useEffect(() => { fetchRandomFacts() .then((response) => { setFact(response?.data?.value); }) .catch(() => { setFact('Funny fact chucknorris API Failed'); }); }, []); function handleOnFactQuerySubmit(event: FormEvent) { event.preventDefault(); if (factQuery) { fetchSearchResult({ query: factQuery }) .then((response) => { let newFact = ''; const result = response?.data?.result; const resultLength = result.length; if (resultLength) { const randomFactIndex = Math.floor(Math.random() * resultLength); newFact = result[randomFactIndex]?.value; } else { newFact = 'No Facts with given query'; } setFact(newFact); }) .catch(() => { setFact('Funny fact chucknorris API Failed'); }); } return false; } function handleOnFactQueryChange(event: ChangeEvent) { const updatedFactQuery = event?.target?.value || ''; const updatedFactQueryLength = updatedFactQuery.length; setFactQuery(updatedFactQuery); if (updatedFactQueryLength > 10) { setFactQueryError('Max 10 characters'); } else if (updatedFactQueryLength === 0) { setFactQueryError('Fact query required'); } else { setFactQueryError(''); } } return (
Chuck Norris Random Facts
Did you know... {fact}
); }