Chap03 -> Implementing component state -> Using useState to implement component state

master
Jason Zhu 2022-03-26 16:46:05 +11:00
parent ffc8fe16f5
commit 5772c175af
2 changed files with 21 additions and 10 deletions

View File

@ -1,14 +1,24 @@
import React, { useEffect } from 'react';
import React from 'react';
import { PageTitle } from './PageTitle';
import { Page } from './Page';
import { QuestionList } from './QuestionList';
import { getUnansweredQuestions } from './QuestionsData';
import { getUnansweredQuestions, QuestionData } from './QuestionsData';
export const HomePage = () => {
useEffect(() => {
console.log('first rendered');
const [questions, setQuestions] = React.useState<QuestionData[]>([]);
const [questionsLoading, setQuestionsLoading] = React.useState(true);
React.useEffect(() => {
const doGetUnansweredQuestion = async () => {
const unanswereedQuestions = await getUnansweredQuestions();
setQuestions(unanswereedQuestions);
setQuestionsLoading(false);
};
doGetUnansweredQuestion();
}, []);
console.log('rendered');
return (
<Page>
<div>
@ -16,9 +26,11 @@ export const HomePage = () => {
<button>Ask a question</button>{' '}
{/* This button component is passed as children of Page */}
</div>
{/* <QuestionList
data={getUnansweredQuestions()}
/> */}
{questionsLoading ? (
<div>Loading...</div>
) : (
<QuestionList data={questions || []} />
)}
</Page>
);
};

View File

@ -4,14 +4,13 @@ import { QuestionData } from './QuestionsData';
interface Props {
data: QuestionData[];
renderItem?: (item: QuestionData) => JSX.Element;
}
export const QuestionList = ({ data, renderItem }: Props) => (
export const QuestionList = ({ data }: Props) => (
<ul>
{data.map((question) => (
<li key={question.questionId}>
{renderItem ? renderItem(question) : <Question data={question} />}
<Question data={question} />
</li>
))}
</ul>