Issue
I am utilizing firebase for the database and Ionic + React for mobile app. I already converted my firebase data into array but when I want to map the values. It tells me that it should have a unique key, but I already put a unique key in my return function in the element. Can someone tell me what did I do wrong? Thanks.
Here is my code in converting objects to array
const Tab2: React.FC = () => {
const [doctors, setDoctor] = React.useState([]);
useIonViewWillEnter(()=>{
console.log('Enter')
firebase.database().ref('users').orderByChild('type').equalTo('doctor').on('value',(snapshot)=>{
setDoctor(Object.keys(snapshot.val()).map(key => ({ [key]: snapshot.val()[key] })))
})
console.log(doctors)
})
And in my return
<IonList>
{doctors.map(elem => {
return(
<IonItem key={elem['uid']}>
<IonLabel>
<IonText className="font-weight: bold;">
<h3>{elem['name']}</h3>
</IonText>
<h4>{elem['speciality']}</h4>
<h4>{elem['email']}</h4>
</IonLabel>
<br></br>
</IonItem>
)
})}
</IonList>
What I got is Warning: Each child in a list should have a unique "key" prop.
My firebase structure
Update: the console.log(doctors) will only output an empty array like this [] and i dont know why. I already put it in a method before the component enter.
Solution
Note: thats just a warning, not an error.
This is the right approach.
<IonList>
{doctors.map((elem, index) => {
// index has to come from the second parameter from map
return (
<IonItem key={index}>
<IonLabel>
<IonText className="font-weight: bold;">
<h3>{elem["name"]}</h3>
</IonText>
<h4>{elem["speciality"]}</h4>
<h4>{elem["email"]}</h4>
</IonLabel>
<br></br>
</IonItem>
);
})}
</IonList>;
The index must be placed in the first/parent div element. In this case it will be <IonItem>
ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Also as per you're not getting the data. Adjust your code like so. You just have to create a new arr, and move through snapshot to get a key.
pushing the object with the respective key to a new arr, so it can be iterable without specific key names such as eA9w5ynhqN9iT7kKDBt2Ane9VF3
useIonViewWillEnter(() => {
console.log("Enter");
let newArr = [];
firebase
.database()
.ref("users")
.orderByChild("type")
.equalTo("doctor")
.on("value", (snapshot) => {
let key;
snapshot.forEach((childSnap) => {
key = childSnap.key; // im just getting the key
const snapVal = snapshot.val(); // getting the object
newArr.push(snapVal[key]);
});
setDoctor(newArr);
// console.log(doctors)
});
});
Answered By - BARNOWL

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.