1

I am unsure of how to change/update the data in my database through react.

My database:

const Package = new mongoose.Schema({
  packageID =  {type: String},
  packageStatus = {type: String, enum: [packed, delivered, received], default: 'packed' },
})

  1. how do I refer to packageStatus and their enum values in react/class component? How should I call them?

  2. The default value is 'packed', I want to change it to 'delivered' when a button is clicked (no text fields involved).

class PackageStatus extends React.Component {
    constructor(){
        super()
        this.state = {
            packageStatus: 'packed'
        }
        this.updateStatus = this.updateStatus.bind(this);
    }

    updateStatus(){
        this.setState =({
            packageStatus: 'delivered'
        }
        )
    
    render(){

        return (
            <div?
                <button onClick={()=> packageStatus(this)}>Update Status</button>       
            </div>

        )
    }
}

export default PackageStatus

The code above changes the text displayed but not the status in the database, so how do I change the data in the database?

Next, I would want to display text depending on what the status in the database is. I'm not sure how to link isDelivered to the condition of the database.

For example

class Status extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isDelivered: true
    };
  }

  render() {
    let { isDelivered } = this.state;
    let status;

    if (isDelivered) {
      status = <h1>Delivered<h1>
    } else {
      status = <h1>Packing in progress<h1>
    }

    return (
      <div>
        {status}
      </div>
    );
  }
}

export default Status;

Any help will be greatly appreciated! Thank you for your time

1
  • Are you using node to communicate with the database? Because in order to communicate with the database, you need to have a backend server. Commented May 20, 2021 at 19:25

1 Answer 1

1

Well interfacing, a frontend framework like REACT with a database, an easier approach would be create apiEndpoints of which you would use make fetch or axios to make httpRequests which communicates to these endpoints, in turn communicate with the database to give you your desired response. A solution approach to your problem is as follows:

  1. Create the schema using mongoose in node

       const mongoose = require('mongoose')
       const { Schema } = mongoose
       const PackageSchema = new Schema({
           packageID: {
              type: String,
           },
           packageStatus: {
              type: String,
              enum: ["packed", "delivered", "received"],
              default: 'packed'
           }
       })
    
        module.exports = mongoose.model('package',PackageSchema)
     
  2. Create the apiEndpoints or routes to interface this schema with FrontEnd(React) and Backend(eg; mongodb)

       const express = require('express');
       const router = express.Router();
       require('dotenv').config()
       const package = require('../model/packageModel');
    
           router.get('/allpackages', async(req, res) => {
              try{
                    const getAllPackages = await package.find();
                    res.json(getAllPackages);
               }catch(err){
                     res.json({
                      message: err
                })
             }
           })
    
          router.post('/addPackage',async(req, res) => {
                  const pack = new package({
                  packageID: req.body.packageID,
                  packageStatus: req.body.packageStatus
                 })
               try{
                    const savedPost = await pack.save();
                    res.json(savedPost);
               }catch(err){
               res.json({
                     message: err
               })
              }
           })
    
        router.patch('/updatePackageStatus', async (req, res) => {
         try {
              const updatePackageStatus = await package.updateOne(
               { _id: req.body.packageID },
               {
                  $set: {
                       packageStatus: req.body.packageStatus
                 }
              }
            )
            res.json(updatePackageStatus)
           }catch (err) {
           res.json({
             message: err
          })
        }
      })
    
     module.exports = router;
     
  3. Use POSTMAN or any other of choice to test endpoints with schema, and database, to see if you get the desired results. After testing out the above, with POSTMAN, all desired operations work as expected, and you should have no problem, interfacing it with any Frontend Framework(Angular, React, Vue) now.

        GET  http://localhost:3000/package/allpackages
        POST http://localhost:3000/package/addPackage
        PATCH http://localhost:3000/package/updatePackageStatus
     

sample screenshot shown below fetch api Endpoints via postman

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.