I have a React app where I want to read data from an object into an array and then render this. However, duplicates of the same data is rendered and upon investigating further I've found out that the array to which I'm pushing the elements is of length 8 or 12 (this mysteriously varies) instead of 4 which is the length I expect it to be. The array is of this length even before pushing any elements to it as indicated by a console log right after initialization. I am completely perplexed as to why this happens, can anyone offer some insights? Thanks!
question_card.js
const arr = [];
console.log(arr);
const tempData = {
id: 2,
question_text: "When was the enigma code cracked?",
answers: [
{ answer_text: 1941 },
{ answer_text: 1942 },
{ answer_text: 1939 },
{ answer_text: 1943 },
],
};
function getAnswers() {
tempData.answers.forEach((answer) => {
arr.push((<p>{answer.answer_text}</p>));
});
}
function QuestionCard() {
getAnswers();
return(
<div>
<p>This will be the question</p>
<div>{arr}</div>
</div>
)};
export default QuestionCard;
App.js
import "./App.css";
import QuestionCard from "./question_card";
function App() {
return (
<div className="App">
<QuestionCard />
</div>
);
}
export default App;
Output: console.log(arr)
question_card.js:3
[]
0: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
1: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
2: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
3: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
4: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
5: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
6: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
7: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
8: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
9: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
10: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
11: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …}
length: 12
As mentioned in the comments, you are trying to call the getAnswers function in every re-render and that was causing unwanted data on the tempData.answer array.
So, don't call the getAnswers function in QuestionCard component directly. call it inside a useEffect hook:
function QuestionCard() {
useEffect(() => {
getAnswers();
}, [])
return(
<div>
<p>This will be the question</p>
<div>{arr}</div>
</div>
)};
export default QuestionCard;