I am working with React
and Realtime Database
.
Here are the 2 main database nodes related to this question:
and:
Below is the relevant code:
class App extends React.Component {
constructor(props) {
super(props);
firebase.initializeApp(config);
this.state = {
commandes: []
};
}
componentDidMount() {
this.getData();
}
getData = () => {
let ref = firebase.database().ref("/");
ref.on("value", snapshot => {
const state = snapshot.val();
this.setState(state);
});
};
.....
render() {
const { commandes } = this.state;
return (
<React.Fragment>
.....
{commandes.map(item => (
<div
key={item.name}
className="card float-left"
style={{ width: "18rem", marginRight: "1rem" }}
>
</div>
.....
))}
.....
</React.Fragment>
);
}
}
It does not work and this is the error I am getting:
TypeError: commandes.map is not a function
This is the reason of my posting this. And I'd be glad to get some feed back or tips as to solving this issue.
Now here is one important note: when using the same code as above, only changing the 3 occurences of commandes to developers, then the code works perfectly, listing the items in the collection developers as I expect. Though I have spent some time trying a few things to figure out the problem, it does not work. Since I am not changing the code (other than what I just mentioned) I assume the differencence is between the collections, but I can't really see what.
Here is the function creating one item in the commandes collection:
sendCommande = item => {
const orderTime = new Date(),
orderKey = orderTime.getTime().toString(),
orderOject = {
name: item.name,
price: item.price,
dateTime: orderTime.toLocaleString(),
status: 1,
uid: orderKey
}
firebase.database()
.ref("/commandes/" orderKey)
.set(orderOject);
};
CodePudding user response:
I assume the differencence is between the collections (i.e. the database nodes), but I can't really see what
The reason is that for the developers
node the subnodes keys are in a sequence: 0
, 1
, 2
. The val()
method interprets that as an Array.
The subnodes keys of the commandes
node are not following a sequence: therefore the val()
method returns a JavaScript Object (which is not an Array), hence the error with map()
.
Notre that some subnode keys like 1
,2
,4
,6
will also return an Array: the val()
method detects a sequence (1
,2
) and returns an Array with some null elements at indexes 0
, 3
and 5
.