React Hook not saving key value pairs in object, MongoDB just saving id & __v

Viewed 108

Using: MongoDB, Express, ReactJS, Node.js to save an object containing student's first name, last name, and grade. I expect it to save like this:

{
firstName: "Jaron",
lastName: "Smith",
grade: "2",
_id: "60f205222e2569cc122c5417",
__v: 0
},

Current result: not even saving key / value pair, just the assigned values by MongoDB:

{
_id: "60f205222e2569cc122c5417",
__v: 0
},

My createStudent.js file with React Hook:

import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import axios from 'axios'; //Axios is designed to handle http requests and responses. It's used more often than Fetch because it has a larger set of features and it supports older browsers.

const useStyles = makeStyles((theme) => ({
  root: {
    '& > *': {
      margin: theme.spacing(1),
      width: '25ch',
    },
  },
}));

export default function Create() {
  const classes = useStyles();

  const [student, setStudent] = useState({ //creating a pice of state and initializing it with an object
    firstName: '',
    lastName: '',
    grade: ''
  })

  const updateStudent = e => {
    e.preventDefault();
    setStudent({
      ...student,
      [e.target.name]: e.target.value
    });
  }
  
  const createStudent = () => {
    console.log(JSON.stringify(student));
    axios.post('http://localhost:5000/students', student) //sends data from client (useState) to backend
    .then(
      console.log("result after post:" + JSON.stringify(result))
      window.location.reload()
    ).catch(error => {
        console.log(error)
    })
  }
  return (
    <>
      <h2>Create Student</h2>
      <form className={classes.root} noValidate autoComplete="off">
        <TextField 
          id="outlined-basic" 
          name="firstName"
          label="First Name" 
          variant="outlined" 
          value={student.firstName} 
          onChange={updateStudent}
        />
        <TextField 
          id="outlined-basic" 
          name="lastName"
          label="Last Name" 
          variant="outlined" 
          value={student.lastName} 
          onChange={updateStudent}
        />
        <TextField 
          id="outlined-basic" 
          name="grade"
          label="Grade" 
          variant="outlined" 
          value={student.grade} 
          onChange={updateStudent}
        />
        <Button variant="contained" color="primary" onClick={createStudent}>
        Create
        </Button>
      </form>
    </ >
  );
}

I believe that it's the syntax of the React Hook. If not, my server is here: server side repo

I've tried refactoring 'update student' without luck. I console.log() e.target and it's recognizing the text entered in the form. On the line with 'axios.post' in hard coded data to upload in place of 'student' on that same line and it still created an object like the current result above. I know it's got to be something simple! Any feedback is welcomed and appreciated!

2 Answers

I think your problem is here :

  const updateStudent = e => {
    setStudent({
      ...student,
      [e.target.name]: e.target.value
    });
   e.preventDefault(); // this line
  }

you should set your state first before do e.preventDefault();

Your are calling e.preventDefault() in you updateStudent function but you don't need it, you have to use it on the createStudent function.

const updateStudent = e => {
    e.preventDefault(); // delete this line
    setStudent({
      ...student,
      [e.target.name]: e.target.value
    });
  }
  
  const createStudent = () => {
     e.preventDefault();
     ...
  }
Related