'Duplicate object on array when using .forEach
I am trying to push data using the .forEach function into an array of objects so that I could return a list of available feedbacks into the Administrator page for my portfolio but when they are pushed into the feedback array, it turns out that the objects from d get duplicated, but the weird part is that only the last object pushed that gets duplicated.
I've tried to reassign the array before fetching, using useState on d, using useState on feedback and on dataArray but it still returned the same.
Code:
import styles from '../../styles/Home.module.css';
import { supabase } from '../../lib/supabase';
import { useEffect, useState } from 'react';
interface s {
session: any
}
interface dataObject {
id: String,
Name: String,
Message: String,
}
const AdminPage = (props: s) => {
let d = {} as dataObject
const [loading, setLoading] = useState(false);
const [feedback, setFeedback] = useState<any>([{}]);
const dataArray:Array<any> = [];
const getFeedback = async () => {
try {
setLoading(true)
let {data, error, status} = await supabase
.from('Feedback')
.select('id, Name, Message')
if (error && status !== 406) throw error;
if (data) {
data.forEach(element => {
console.log('Data: ', data)
const {id, Name, Message} = element;
d.id = id;
d.Name = Name;
d.Message = Message;
feedback.push(d);
});
}
} catch (error) {
// @ts-ignore
alert(error.message)
} finally {
setLoading(false)
console.log('Feedback: ', feedback);
}
}
const signOut = async () => {
const { error } = await supabase.auth.signOut()
if (error) throw error;
}
if (feedback !== [{}]) {
feedback.forEach(element => {
if (!element.id) return;
dataArray.push(
<div className={styles.card}>
<div key={element.id}>
<p>{element.Name} says: "{element.Message}"</p>
</div>
</div>
)
})
console.log('DataArray: ', dataArray )
}
return (
<div>
{loading ? (
'Loading Data...'
): (
<div>
{dataArray.length == 2 ? (
<div className={styles.error}>
<p>No data available...</p>
</div>
): (
<div>
<h1>Feedback</h1>
{dataArray}
</div>)
}
<button className={styles.button_d} onClick={signOut}>Signout</button>
<button className={styles.button} onClick={getFeedback}>Get Feedback JSON</button>
</div>
)}
</div>
)
}
export default AdminPage;
Console:
Data:
Array [ {…}, {…} ]
0: Object { id: "927c5399-7251-4139-8a31-5417f9383d06", Name: "Raul Perez", Message: "This is a test feedback to try out the brand new feedback feature from perezbueno.xyz!" }
1: Object { id: "d8981533-d629-4082-b45d-1ac9b758e73e", Name: "Hello World", Message: "deez nuts" }
length: 2
<prototype>: Array []
index.tsx:29:28
DataArray:
Array(4) [ [], dispatchAction(), {…}, {…} ]
0: Array []
1: function dispatchAction()
2: Object { "$$typeof": Symbol("react.element"), type: "div", key: null, … }
3: Object { "$$typeof": Symbol("react.element"), type: "div", key: null, … }
length: 4
<prototype>: Array []
index.tsx:60:16
Feedback:
Array(3) [ {}, {…}, {…} ]
0: Object { }
1: Object { id: "d8981533-d629-4082-b45d-1ac9b758e73e", Name: "Hello World", Message: "deez nuts" }
2: Object { id: "d8981533-d629-4082-b45d-1ac9b758e73e", Name: "Hello World", Message: "deez nuts" }
length: 3
<prototype>: Array []
Solution 1:[1]
You need to use setFeedback in order to update your state instead of feedback.push. Replace feedback.push with setFeedback([...feedback,d]) and it should solve your issue
Solution 2:[2]
i think when change the state,should use setstate. feedback.push(d) should change to
setfeedback(...feedback,d)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex |
| Solution 2 | Kenny1997 |
