Iam building a quiz-website as practice for React and want to be able to change question with a button. When I change useState(0) manually to 1 the next object renders. But i cant get it to work with the button. When i click the button it jumps straight to the alert message.
function GetMovies() {
useEffect(() => {
fetchItems();
}, []);
const [items, setItems] = useState({ options: [] });
const fetchItems = async () => {
const data = await fetch("http://localhost:5000/api/movies");
const items = await data.json();
//test
//console.log(items[currentQuestion]);
setItems(items[currentQuestion]);
};
const [currentQuestion, setCurrentQuestion] = useState(0);
//change question solution that dont work
const HandleAnswerButtonClick = () => {
const nextQuestion = setCurrentQuestion 1;
if (nextQuestion < items.length) {
setCurrentQuestion(nextQuestion);
} else {
alert("End of quiz");
}
setCurrentQuestion(nextQuestion);
};
return (
<div className="App">
<h1>Quiza</h1>
<div>
<span>Question 1</span>
</div>
<div>
<h3>Question: {items.description}</h3>
{items.options.map((c) => (
<button value={c.is_correct} key={c.text}>
{c.text}
</button>
))}
<div>
{//Next BUTTON}
<button onClick={() => HandleAnswerButtonClick()}>
Next question
</button>
</div>
{/* if-sats, om bild finns till frågan visas den, annars en class med display none */}
<div className="Q_pics">
{items.options.map((c) =>
!c.image ? (
<p className="Display_none">empty</p>
) : (
<img src={c.image} alt={c.text}></img>
)
)}
</div>
</div>
</div>
);
}
The mongoose schema from my API
const MovieSchema = mongoose.Schema(
{
category: { type: String, required: true },
description: { type: String, required: true },
image: {
type: String,
required: false,
},
options: [
{
text: {
type: String,
required: true,
},
is_correct: {
type: Boolean,
required: true,
default: false,
},
image: {
type: String,
required: false,
},
},
],
},
{ collection: "movies" }
);
CodePudding user response:
That is because
const nextQuestion = setCurrentQuestion 1;
should be
const nextQuestion = currentQuestion 1;
Oh, and as @Nick Parsons mentioned in a comment, you also only store the first question in your state, since the fetchItems
is only run once, and you do setItems(items[currentQuestion]);
You should do something like
function GetMovies() {
const [items, setItems] = useState([]);
const [currentQuestion, setCurrentQuestion] = useState(0);
const fetchItems = async () => {
const data = await fetch("http://localhost:5000/api/movies");
const items = await data.json();
//test
//console.log(items[currentQuestion]);
setItems(items);
};
//change question solution that dont work
const HandleAnswerButtonClick = () => {
const nextQuestion = currentQuestion 1;
if (nextQuestion < items.length) {
setCurrentQuestion(nextQuestion);
} else {
alert("End of quiz");
}
setCurrentQuestion(nextQuestion);
};
useEffect(() => {
fetchItems();
}, []);
const activeQuestion = items[currentQuestion];
return (
<div className="App">
<h1>Quiza</h1>
<div>
<span>Question {currentQuestion 1}</span>
</div>
<div>
<h3>Question: {activeQuestion.description}</h3>
{activeQuestion && activeQuestion.options.map((c) => (
<button value={c.is_correct} key={c.text}>
{c.text}
</button>
))}
<div>
{//Next BUTTON}
<button onClick={() => HandleAnswerButtonClick()}>
Next question
</button>
</div>
{/* if-sats, om bild finns till frågan visas den, annars en class med display none */}
<div className="Q_pics">
{activeQuestion && activeQuestion.options.map((c) =>
!c.image ? (
<p className="Display_none">empty</p>
) : (
<img src={c.image} alt={c.text}></img>
)
)}
</div>
</div>
</div>
);
}
CodePudding user response:
the code might be like this:
const [items, setItems] = useState({ options: [] });
// currentIdx might be a better name
const [currentIdx, setCurrentIdx] = useState(0);
const fetchItems = async () => {
const data = await fetch("http://localhost:5000/api/movies");
const items = await data.json();
// save all data as Nick said. and items should be type of Data[];
setItems(items);
};
const HandleAnswerButtonClick = () => {
const nextQuestion = currentIdx 1;
if (nextQuestion < items.length) {
setCurrentIdx(nextQuestion);
} else {
alert("End of quiz");
}
};
// use displayItem for render
const displayItem = useMemo(() => items[currentIdx], [items, currentIdx]);
you'd better learn to use dev tools and watch values of your code I think