Reputation: 125
Im making an app using ReactJs with firebase. In updatePlayers, i followed the firebase documentation exactly to add elements to an array. In firestore, i have a collection called footballgames with a document of a game called C3j5hXxNFKMBUM7YxaNX. It contains an array field which contains an array of players and i would like to add "John" to the array whenever the function is called. However i keep getting the error TypeError: _firebase_firebase_utils__WEBPACK_IMPORTED_MODULE_5__.default.collection is not a function
import React, { useState, useEffect, Fragment } from "react";
import { useParams } from "react-router-dom";
import { connect } from "react-redux";
import GameDetails from "../../components/game-details/game-details.component";
import PlayerList from "../../components/player-list/player-list.component";
import firestore from '../../firebase/firebase.utils'
import * as firebase from 'firebase';
import 'firebase/firestore';
class GameDetailPage extends React.Component {
constructor(props) {
super(props);
this.state = {
userName: "",
};
}
updatePlayers=()=>{
var playersRef=firestore.collection("footballgames").doc("C3j5hXxNFKMBUM7YxaNX")
playersRef.update({
Players:firebase.firestore.FieldValue.arrayUnion("John")
})
}
render() {
const { games, currentUser } = this.props;
let { linkUrl } = this.props.match.params;
const gameObj = games[linkUrl];
console.log("user", currentUser);
return (
<Fragment>
<div className="game-list">
<GameDetails game={gameObj} />
</div>
<h2>Current players</h2>
{currentUser ? (
<div className="player-list">
{gameObj.Players.map((player, index) => (
<PlayerList key={index} player={player} />
))}
</div>
) : (
<p>Loading</p>
)}
<button onClick={()=>this.updatePlayers()}>Join</button>
</Fragment>
);
}
}
const mapStateToProps = (state) => ({
games: state.games.games,
currentUser: state.user.currentUser,
});
export default connect(mapStateToProps)(GameDetailPage);
Upvotes: 0
Views: 506
Reputation: 317467
The error doesn't seem to have anything to do with arrayUnion. Using what you're showing here, it seems that this is not working (the method collection is not found):
var playersRef = firestore.collection(...)
You'll want to use this instead to find the collection method:
var playersRef = firebase.firestore.collection(...)
Your import is pulling something else in and calling it firestore
, and it's probably not the same as firebase.firestore
:
import firestore from '../../firebase/firebase.utils'
Upvotes: 1