I'm attempting to make a simple app displaying a random quote. With a time interval. Though I'm struggling to understand how I could randomise a quote on a timer and display the content.
My code so far:
import { useState } from 'react';
import { data } from './hardCode';
export default function Index() {
const [quotes, setQuotes] = useState(data);
console.log(quotes);
return (
<main>
<div className='wrapper'>
<div className='feature'>
<div className='quote-wrapper'>
<h1 className='quote'>"{quotes[0].quote}"</h1>
</div>
<div className='author-wrapper'>
<span className='author'>- {quotes[0].author}</span>
</div>
</div>
</div>
</main>
);
}
currently I'm using hard coded data which looks like this:
const data = [
{id: 1, author: 'suzy', quote: 'hello world'}
]
I would like to learn how to display a random quote with the authors name, then after a couple of seconds display a different one. Also not display the same quote twice in one session if possible.
Compute a random index Math.floor(Math.random() * data.length)
const data = [ {id: 1, author: 'suzy', quote: 'hello world'}, {id: 4, author: 'bob', quote: 'hello world 2'}, {id: 3, author: 'carrie', quote: 'hello world 3'}, {id: 5, author: 'timmy', quote: 'hello world 4'}, {id: 2, author: 'bob', quote: 'hello world 5'}, ]; const randIndex = Math.floor(Math.random() * data.length); console.log(data[randIndex].quote);
RandomQuote
const getRandIndex = arr => Math.floor(Math.random() * arr.length);
const RandomQuote = ({ data, interval = 2000 }) => {
const [quotes, setQuotes] = useState(data);
const [currentQuote, setCurrentQuote] = useState();
/**
* Select a quote at random and remove from the current list of
* selectable quotes, reducing the array length by 1
*/
const getRandomQuote = useCallback(() => {
const randIndex = getRandIndex(quotes);
setCurrentQuote(quotes[randIndex]);
setQuotes(quotes => quotes.filter((_, i) => i !== randIndex));
}, [quotes]);
// Get initial random quote and setup interval and cleanup function
useEffect(() => {
!currentQuote && getRandomQuote();
const timer = quotes.length && setInterval(getRandomQuote, interval);
return () => clearInterval(timer);
}, [currentQuote, getRandomQuote, interval, quotes]);
return (
<main>
<div className="wrapper">
<div className="feature">
{currentQuote && (
<Fragment>
<div className="quote-wrapper">
<h1 className="quote">"{currentQuote.quote}"</h1>
</div>
<div className="author-wrapper">
<span className="author">- {currentQuote.author}</span>
</div>
</Fragment>
)}
</div>
</div>
</main>
);
};
You can use setTimeout nested or setInterval, and the you can use a observer to keep track of previously used id's and once it goes over the session we can reset the timer and observer
const data = [ {id: 1, author: 'suzy', quote: 'hello world'}, {id: 4, author: 'bob', quote: 'hello world 2'}, {id: 3, author: 'carrie', quote: 'hello world 3'}, {id: 5, author: 'timmy', quote: 'hello world 4'}, {id: 2, author: 'bob', quote: 'hello world 5'}, ]; function observerReset(){ if(Date.now() - timer >= 2000 * data.length && Object.keys(observer).length === data.length){ console.log('observer reset') observer = {} timer = Date.now() } } function randomIndex(){ let randIndex = undefined while(observer[randIndex] === undefined){ randIndex = Math.floor( Math.random() * data.length); if(observer[randIndex] === undefined ){ observer[randIndex] = randIndex } else { randIndex = undefined } } return randIndex } let observer = {} let timer = Date.now() setTimeout(function quotePrinter() { observerReset() let randIndex = randomIndex(); let { author, quote } = data[randIndex] console.log(`${author}: ${quote}`); setTimeout(quotePrinter, 2000) }, 2000)
First you should import data as full arry of obj then create random function like
const rand = function () {
return Math.floor(Math.random() * data.length)
}
and use it
< h1 className = 'quote' > { data[rand()].quote }</h1 >
also you can use
< span className = 'author' > - { data[rand()].author }</span >
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.