Chap03 -> Implementing component state -> Using useState to implement component state
parent
ffc8fe16f5
commit
5772c175af
|
@ -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>
|
||||
);
|
||||
};
|
||||
|
|
|
@ -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>
|
||||
|
|
Loading…
Reference in New Issue