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 { 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, QuestionData } from './QuestionsData';
|
||||||
|
|
||||||
export const HomePage = () => {
|
export const HomePage = () => {
|
||||||
useEffect(() => {
|
const [questions, setQuestions] = React.useState<QuestionData[]>([]);
|
||||||
console.log('first rendered');
|
const [questionsLoading, setQuestionsLoading] = React.useState(true);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const doGetUnansweredQuestion = async () => {
|
||||||
|
const unanswereedQuestions = await getUnansweredQuestions();
|
||||||
|
setQuestions(unanswereedQuestions);
|
||||||
|
setQuestionsLoading(false);
|
||||||
|
};
|
||||||
|
doGetUnansweredQuestion();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
console.log('rendered');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Page>
|
<Page>
|
||||||
<div>
|
<div>
|
||||||
|
@ -16,9 +26,11 @@ export const HomePage = () => {
|
||||||
<button>Ask a question</button>{' '}
|
<button>Ask a question</button>{' '}
|
||||||
{/* This button component is passed as children of Page */}
|
{/* This button component is passed as children of Page */}
|
||||||
</div>
|
</div>
|
||||||
{/* <QuestionList
|
{questionsLoading ? (
|
||||||
data={getUnansweredQuestions()}
|
<div>Loading...</div>
|
||||||
/> */}
|
) : (
|
||||||
|
<QuestionList data={questions || []} />
|
||||||
|
)}
|
||||||
</Page>
|
</Page>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
@ -4,14 +4,13 @@ import { QuestionData } from './QuestionsData';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
data: QuestionData[];
|
data: QuestionData[];
|
||||||
renderItem?: (item: QuestionData) => JSX.Element;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const QuestionList = ({ data, renderItem }: Props) => (
|
export const QuestionList = ({ data }: Props) => (
|
||||||
<ul>
|
<ul>
|
||||||
{data.map((question) => (
|
{data.map((question) => (
|
||||||
<li key={question.questionId}>
|
<li key={question.questionId}>
|
||||||
{renderItem ? renderItem(question) : <Question data={question} />}
|
<Question data={question} />
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
|
Loading…
Reference in New Issue