PUT request in react

Arnald Shartz
Arnald Shartz used Ask the Experts™
on
So I have an update form and I want to prepopulate it. I also want to execute the update method as well. I am having some issues on how I can approach that problem. Below I have a screen shot,back end and also front end code

Update and prepopulating form using react
second.post('/student_info',(req,res)=>{
  const student_id = req.body._id;
  db.collection('students').find({"_id" : ObjectID(student_id)}).toArray((err,result) => {
    if(!err) {
       res.send(result);
    } else {
        console.log(err);
    }

  });

Open in new window



second.post('/students/updateStudent', (req, res) => {
   try {
    db.collection('students').updateMany( {"_id" : ObjectID(req.body._id)},
      { $set: { role_num:req.body.role_num, first_name: req.body.first_name, last_name: req.body.last_name, marks: req.body.marks}});
 } catch (e) {
  console.log(e);
 }
    res.send('student updated');
 });

Open in new window

import React, {Component} from 'react';
import './App.css';
import axios from 'axios';
export default class EditStudent extends Component {
constructor(props) {
  super(props)
  this.ChangeID = this.ChangeID.bind(this);
  this.ChangeRoleNumber = this.ChangeRoleNumber.bind(this);
  this.ChangeFirstName= this.ChangeFirstName.bind(this);
  this.ChangeLastName = this.ChangeLastName.bind(this);
  this.ChangeMarks = this.ChangeMarks.bind(this);
  this.Enter =  this.Enter.bind(this);

  this.state = {
     _id: '',
     role_num: '',
     first_name: '',
     last_name: '',
     marks: ''

  }
}
componentDidMount() {
axios.post('http://localhost:3200/students/student_info', {
  '_id': this.props.match.params._id,
  'role_num': this.props.match.params.role_num,
  'first_name': this.props.match.params.first_name,
  'last_name': this.props.match.params.last_name,
  '_marks': this.props.match.params.marks
})

.then(res => {
              this.setState({
                _id: res.data._id,
                role_num: res.data.role_num,
                first_name: res.data.first_name,
                 last_name: res.data.last_name,
                 marks: res.data.marks
               });
          })
          .catch(err => {
              console.log(err);

   })
}
 ChangeID(a) {
 this.setState({
   _id: a.target.value
 })
}

ChangeRoleNumber(a) {
  this.setState({
    role_num: a.target.value
  })
}

ChangeFirstName(a) {
  this.setState({
    first_name: a.target.value
  })
}
ChangeLastName(a) {
  this.setState({
    last_name: a.target.value
  })
}
ChangeMarks(a) {
  this.setState({
    marks: a.target.value
  })
}
Enter(a) {
a.preventDefault();

const myob = {
  _id: this.state._id,
  role_num: this.state.role_num,
  first_name: this.state.first_name,
  last_name: this.state.last_name,
  marks: this.state.marks

};
axios.post('http://localhost:3200/students/updateStudent',  {
  '_id':this.props.match.params._id ,
  myob
})
.then(err => console.log(err.data));
  this.props.history.push('/getstudents');
}

  render() {
return(
  <div style={{marginTop:50}}>
      <h2>Update Student</h2>
      <form onSubmit={this.Enter}>
        <div className = 'form-group'>
           <label>Enter ID: </label>
           <input type = "text" className ='form-control' value= {this.state._id} onChange={this.ChangeID}
           />

          </div>
          <div className = 'form-group'>
             <label>Enter Role Number: </label>
             <input type = "text" className ='form-control'  value= {this.state.role_num} onChange={this.ChangeRoleNumber} />
            </div>
            <div className = 'form-group'>
               <label>Enter First Name : </label>
               <input type = "text" className ='form-control'value= {this.state.first_name} onChange={this.ChangeFirstName}/>
              </div>
              <div className = 'form-group'>
                 <label>Enter Last Name: </label>
                 <input type = "text" className ='form-control'value= {this.state.last_name} onChange={this.ChangeLastName}/>
                </div>
                <div className = 'form-group'>
                   <label>Enter Marks: </label>
                   <input type = "text" className ='form-control'value= {this.state.marks} onChange={this.ChangeMarks}/>
                  </div>
                  <div className = 'form-group'>
                     <input type = "submit" className ='btn btn-primary'value= "Edit Student"/>
                    </div>

      </form>

  </div>

)
}
}

Open in new window

so above is my front end and back end code. So I have worked with this front end data in jquery and I have a post for student_info so I could prepopulate the fields in the front end but I do not know why it is not prepopulating. Also when ever I type in the data I want to change and also when I click edit student the data that I entered becomes null.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi,

You need to fix the JS errors.

One refer to a file no found, so check the path.

The other one is refer to the CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
here some way to fix it
https://daveceddia.com/access-control-allow-origin-cors-errors-in-react-express/

Author

Commented:
so I install cors and include it in my backend

Author

Commented:
ok so I fixed some things  I added the cors to my back end and in my back end I changed

second.get('/students/student_info/:id',(req,res)=>{
  const student_id = req.body._id;
  db.collection('students').find({"_id" : ObjectID(student_id)}).toArray((err,result) => {
    if(!err) {
       res.send(result);
    } else {
        console.log(err);
    }

  });

Open in new window


and front end to

axios.get('http://localhost:3200/students/student_info/'+ this.props.match.params.id)

.then(res => {
              this.setState({
                _id: res.data._id,
                role_num: res.data.role_num,
                first_name: res.data.first_name,
                 last_name: res.data.last_name,
                 marks: res.data.marks
               });
          })
          .catch(err => {
              console.log(err);

   })
}

Open in new window


but when I change the information on the form I get the 200 status ok on the network but nothig changes at all
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
and I also get this  

error

index.js:1375 Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components
    in input (at editform.js:93)
    in div (at editform.js:91)
    in form (at editform.js:90)
    in div (at editform.js:88)
    in EditStudent (created by Context.Consumer)
    in Route (at App.js:34)
    in Switch (at App.js:31)
    in div (at App.js:14)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:13)
    in App (at src/index.js:7
Hi

a Controlled/Uncontrolled input means if the <input> field has a value or not.
// controlled 
<input value="myvalue"/>

// uncontrolled
<input value={null}/>

Open in new window


I would make sure there is always a default value or  ' ' if empty...

something like this
<input value={value || ''}/>

Open in new window


When all fix check if the console have errors

Author

Commented:
ok I fixed that but how can I prepopulate my fields on the update form when I click update I want my data to show already and I have mentioned this in my question
ill show you my code for update the update method is working but i need to prepopulate the form

import React, {Component} from 'react';
import './App.css';
import axios from 'axios';
export default class EditStudent extends Component {
constructor(props) {
  super(props)
  this.ChangeID = this.ChangeID.bind(this);
  this.ChangeRoleNumber = this.ChangeRoleNumber.bind(this);
  this.ChangeFirstName= this.ChangeFirstName.bind(this);
  this.ChangeLastName = this.ChangeLastName.bind(this);
  this.ChangeMarks = this.ChangeMarks.bind(this);
  this.Enter =  this.Enter.bind(this);

  this.state = {
     _id: '',
     role_num: '',
     first_name: '',
     last_name: '',
     marks: ''

  }
}
componentDidMount() {
axios.get('http://localhost:3200/students/student_info/'+ this.props.match.params.id)

.then(res => {
              this.setState({
                _id: res.data._id,
                role_num: res.data.role_num,
                first_name: res.data.first_name,
                 last_name: res.data.last_name,
                 marks: res.data.marks
               });
          })
          .catch(err => {
              console.log(err);

   })
}
 ChangeID(a) {
 this.setState({
   _id: a.target.value
 })
}

ChangeRoleNumber(a) {
  this.setState({
  role_num: a.target.value
  })
}

ChangeFirstName(a) {
  this.setState({
    first_name: a.target.value
  })
}
ChangeLastName(a) {
  this.setState({
    last_name: a.target.value
  })
}
ChangeMarks(a) {
  this.setState({
    marks: a.target.value
  })
}
Enter(a) {
a.preventDefault();

const myobj = {
  _id: this.state._id,
  role_num: this.state.role_num,
  first_name: this.state.first_name,
  last_name: this.state.last_name,
  marks: this.state.marks

};
axios.post('http://localhost:3200/students/updateStudent', myobj)

.then(res=> console.log(res.data));
  this.props.history.push('/getstudents');
}

  render() {
return(
  <div style={{marginTop:50}}>
      <h2>Update Student</h2>
      <form onSubmit={this.Enter}>
        <div className = 'form-group'>
           <label>Enter ID: </label>
           <input type = "text" className ='form-control' value= {this.state._id || ''} onChange={this.ChangeID}
           />

          </div>
          <div className = 'form-group'>
             <label>Enter Role Number: </label>
             <input type = "text" className ='form-control'  value= {this.state.role_num || ''} onChange={this.ChangeRoleNumber} />
            </div>
            <div className = 'form-group'>
               <label>Enter First Name : </label>
               <input type = "text" className ='form-control'value= {this.state.first_name  || ''} onChange={this.ChangeFirstName}/>
              </div>
              <div className = 'form-group'>
                 <label>Enter Last Name: </label>
                 <input type = "text" className ='form-control'value= {this.state.last_name  || ''} onChange={this.ChangeLastName}/>
                </div>
                <div className = 'form-group'>
                   <label>Enter Marks: </label>
                   <input type = "text" className ='form-control'value= {this.state.marks  || ''} onChange={this.ChangeMarks}/>
                  </div>
                  <div className = 'form-group'>
                     <input type = "submit" className ='btn btn-primary'value= "Edit Student"/>
                    </div>

      </form>

  </div>

)
}
}
You can use https://github.com/final-form/react-final-form#-react-final-form

or you may want to check Formix (my friend use this)
https://jaredpalmer.com/formik/docs/overview


What are you using Redux https://redux.js.org/ or other for the state?

You may want to read this https://github.com/erikras/redux-form#%EF%B8%8F-attention-%EF%B8%8F

Author

Commented:
but what would I have to change in my code in order for the form to prepopulate the data is coming from a back end data base

Author

Commented:
put-populate.png
so as you see in the screen shot above I want to click update and once I click it I want to form to have the data already in it
Depend of the database and the location.

here a basic setup
Back-end : Node.js, Express, Database connection including authorization
Front-end : React, Redux to manage state

if you are using Express and MySQL
https://expressjs.com/en/guide/database-integration.html#mysql

When you launch React app, it should populate its state based on data retrieved from the database to retrieve the data depend on the user role and status

 The React app then just sends HTTP requests to the Express server, from there it handles everything that needs verification /  authorization

You may want to take some course on udemy or pluralsight...

Author

Commented:
I already have  backend set up already here I can show you my update code for the back end

second.post('/students/updateStudent', (req, res) => {
   try {
    db.collection('students').updateMany( {"_id" : ObjectID(req.body._id)},
      { $set: { role_num:req.body.role_num, first_name: req.body.first_name, last_name: req.body.last_name, marks: req.body.marks}});
 } catch (e) {
  console.log(e);
 }
    res.send('student updated');
 });

Author

Commented:
and I used mongodb for my db

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial