Home > Enterprise >  Unexpected token " in JSON at position 0
Unexpected token " in JSON at position 0

Time:11-09

enter image description hereMy Goal for this one is to Add ObjectId inside the array In my backend Im declare schema on this code:

   tchStudents: [{
      type: Schema.Types.ObjectId, 
      ref: "Student"
   }]

THen Im do adding an ObjectId to insert to the array of ObjectID: My BackEnd is very fine

  router.put('/assignAddStudents/:tchID', async (req,res) => {

     try {
         const searchTch = await Teacher.findOne({ tchID: req.params.tchID })

         if(!searchTch){

         return res.status(404).send({
          success: false,
          error: 'Teacher ID not found'
         });
     
         } else {

        let query = { tchID: req.params.tchID }
        let assignedStudentObjID = {$push:{tchStudents: req.body.tchStudents }}

        Teacher.updateOne(query, assignedStudentObjID ,() => {
          try{
             return res.status(200).send({
                success: true,
                msg: 'Student ID has been assigned' 
             });
          } catch(err) {
            console.log(err);
            return res.status(404).send({
              success: false,
              error: 'Teacher ID not found'
           })
         }
       }) 
   }

 } catch (err) {
  console.log(err)
 }

 })

But my Front End Not working err: BAD REQUEST(400) Unexpected token " in JSON at position 0

import React, {useState} from 'react'

import axios from 'axios'

import { URL } from '../../utils/utils'

import { Modal, Button } from 'react-materialize';

import ListTchStudents from '../lists/ListTchStudents';

const trigger = 
    <Button 
       style={{marginLeft:'2rem'}} 
       tooltip="Add More..."
       tooltipOptions={{
          position: 'top'
       }}
      className="btn-small red darken-4">
      <i className="material-icons center ">add_box</i>
    </Button>;

const MdlAddStudents =({teacher}) => {

const [data, setData] = useState('');

const { tchStudents} = data;

const {
  tchID, 
} = teacher; // IF WE RENDER THIS IT TURNS INTO OBJECT

const assignedStudent = () => {
  
  // BUT WE SENT IT TO THE DATABASE CONVERT TO JSON.STRINGIFY to make ObjectId
  const requestOpt = {
     method: 'PUT',
     headers: { 'Content-Type': 'application/json'},
     body: JSON.stringify(data)
  }

  axios.put(`${URL}teachers/assignAddStudents/${tchID}`, data,requestOpt)
     .then(res => {
        setData(res.data.data)
     })

}

return (
  <Modal header="Add Students" trigger={trigger}>
     Please ADD and REMOVE Student ID No. for {tchID}

     <div>
     <ul
        style={{marginBottom:'2rem'}}
        className="collection">
        {
           Object.values(teacher.tchStudents).map(tchStudent => {
              return(
                 <ListTchStudents 
                    tchStudent={tchStudent}
                 />
              ); 
           })
        }
     </ul>

     <div className="row">
         <div className="col s6 offset-s3"></div>
            <div className="input-field">
               <label 
                  htmlFor="" 
                  className="active black-text"
                  style={{fontSize:'1.3rem'}}>
                  Add Students here:
               </label>
               <input 
                  type="text"
                  name="tchStudents"
                  value={(tchStudents)}
                  className="validate"
                  onChange={(e) => setData(e.target.value)}
               />
            </div>
         </div>
     </div>
    
     {/* BUT WE SENT IT TO THE DATABASE CONVERT TO JSON.STRINGIFY to send ObjectId to the database 
     */}
     <div className="row">
        <div className="col s2 offset-s3" ></div>
              <Button 
                 onClick={assignedStudent}
                 tooltip="Add Students"
                 tooltipOptions={{
                    position: 'right'
                 }}
                 className="btn green darken-3">
                 <i className="material-icons ">add_circle</i>
              </Button>
        </div> 
        <p>There are {Object.values(teacher.tchStudents).length} student/s 
        assigned</p>

 </Modal>
 )
}

// MdlAddStudents.propTypes = {
//    assignedStudents: PropTypes.func.isRequired,
// }


export default MdlAddStudents;
// export default connect(null, (assignedStudents))(MdlAddStudents);

Thank you for helping out

CodePudding user response:

The problem stems from you attempting to wrap your tchStudents state property in an object named data.

My advice is to keep it very simple

// it's just a string
const [tchStudents, setTchStudents] = useState("")

const assignedStudent = () => {
  // create your request payload
  const data = { tchStudents }

  // no config object required
  axios.put(`${URL}teachers/assignAddStudents/${tchID}`, data)
    .then(res => {
      // not sure what you want to do here exactly but
      // `res.data` should look like
      // { success: true, msg: 'Student ID has been assigned' }
      setTchStudents("") // clear the input ¯\_(ツ)_/¯
    })
}

The only other change is to use the new setter name in your <input>...

<input 
  type="text"
  name="tchStudents"
  value={tchStudents}
  className="validate"
  onChange={(e) => setTchStudents(e.target.value)}
/>
  • Related