Chap03 -> Implementing component state -> Using useEffect to execute logic

master
Jason Zhu 2022-03-26 16:03:57 +11:00
parent de5bc7f437
commit ffc8fe16f5
2 changed files with 22 additions and 17 deletions

View File

@ -1,19 +1,24 @@
import React from 'react'; import React, { useEffect } from 'react';
import { PageTitle } from './PageTitle'; import { PageTitle } from './PageTitle';
import { Page } from './Page'; import { Page } from './Page';
import { QuestionList } from './QuestionList'; import { QuestionList } from './QuestionList';
import { getUnansweredQuestions } from './QuestionsData'; import { getUnansweredQuestions } from './QuestionsData';
export const HomePage = () => ( export const HomePage = () => {
<Page> useEffect(() => {
<div> console.log('first rendered');
<PageTitle>Unanswered Questions</PageTitle> }, []);
<button>Ask a question</button>{' '}
{/* This button component is passed as children of Page */} return (
</div> <Page>
<QuestionList <div>
data={getUnansweredQuestions()} <PageTitle>Unanswered Questions</PageTitle>
renderItem={(question) => <div>{question.title}</div>} <button>Ask a question</button>{' '}
/> {/* This button component is passed as children of Page */}
</Page> </div>
); {/* <QuestionList
data={getUnansweredQuestions()}
/> */}
</Page>
);
};

View File

@ -48,11 +48,11 @@ const questions: QuestionData[] = [
}, },
]; ];
export const getUnansweredQuestions = async(): Promise<QuestionData[]> => { export const getUnansweredQuestions = async (): Promise<QuestionData[]> => {
await wait(500); await wait(500);
return questions.filter((q) => q.answers.length === 0); return questions.filter((q) => q.answers.length === 0);
}; };
const wait = (ms: number): Promise<void> => { const wait = (ms: number): Promise<void> => {
return new Promise(resolve => setTimeout(resolve, ms)) return new Promise((resolve) => setTimeout(resolve, ms));
} };