Search code examples
javascriptreactjsmongodbmeteorpreventdefault

My program doesn't work properly and when I click 'add player' button, no docs add to mongo


I want to write a simple program to add players name on the screen and mongodb butI'm a beginner and I want to write a program in meteor for adding players to mongo, but when I click on add player button, the program doesn't work properly and no docs add to mongo:

import './main.html';
import React from 'react';
import ReactDom from 'react-dom';
import {Meteor} from 'meteor/meteor'
import {Players} from './../imports/api/Players'
import {Tracker} from 'meteor/tracker'

const renderPlayers = (playersList) => {
   return playersList.map((player)=> {
        return <p key={player._id}>{player.name} has {player.score} point(s).</p>;
    });
};

const handleSubmit = (e) => {

    e.preventDefault();

    let playerName = e.target.playername.value;
    if (playerName){
        e.target.playerName.value = '';
        Players.insert ({
            name: playername,
            score: 0
        })
    }
}

Meteor.startup(() => {

    Tracker.autorun(() =>{
        let playersList = Players.find().fetch();
        let title = 'Score Keep';
        let name = 'Fateme';
        let jsx = (
            <div>
                <h1>{title}</h1>
                {renderPlayers(playersList)}
                <form name="New-Player" onSubmit={handleSubmit}>
                    <input type="text" name="PlayerName" placeholder="player Name"/>
                    <input type="submit" onClick={handleSubmit} value="add player"/>
                </form>
            </div>
        );
        ReactDom.render(jsx, document.getElementById('app'));
    });

});

Solution

  • From your code e.target refers to the button which has an onClicked handler attached. To reference the input field value you can use plain Javascript or you do it the React way by using controlled components or uncontrolled components. If using plain Javascript, add an id to the input tag and reference it thus

      const playerName 
      =document.getElementById("idofiputtag").value;
    

    PlayerName will contain the value in the textbox.