Using the PUT method in combination with express and sequelize

I am having trouble using the PUT method to update data based on req.params.id. My approach involves retrieving data by id, displaying it in a table format, allowing users to make changes, and then updating the database with the new values.

Here is the code snippet:

router.put('/:id' , (req,res, next) => {
  Student.findById(+req.params.id)
  .then(data => {
    let arr = data.dataValues;
    res.render('edit', {
      files : arr
    })
  })
  .catch(err => {
    res.status(404).send('something went wrong');
  })

  const  theKey = key => key || undefined
    const {first_name, last_name, email } = req.body
    let obj = {
      first_name : theKey(first_name),
      last_name: theKey(last_name),
      email: theKey(email),
      createdAt: new Date(),
      updatedAt: new Date()
    }
    Student.update(obj,
        { returning: true,
          where: {
            id : req.params.id
          }
        })
    .then(updated => {
      res.send(`updated`)
    })
})

Snippet from my app.js:

app.use('/students/edit', editstudent )

However, I am encountering an issue where data does not get updated when navigating back to the student list in the database. Could there be an error in my PUT method implementation?

Answer №1

res.render('edit', {
  data : files
})
.then(updated => {
  res.send(`Success: Student updated`)
})

The issue here is that the rendering of the page happens before the student data is actually updated. It would be better to update the student first and then render the page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate a personalized add-button into the material-table interface

My current setup includes a basic material-table structured like this: <MaterialTable options={myOptions} title="MyTitle" columns={state.columns} data={state.data} tableRef={tableRef} // Not functioning properly editabl ...

Creating an alert pop-up that displays text based on the prompt input type: A step-by-step guide

I'm a new to Javascript and I'm trying out some basic scripts. My objective is to display a prompt message (1.) asking for a name, then show an alert (2.) based on the input from the prompt. If the input is a valid name (a string), then the alert ...

Steps for uploading an image to a Node.js server from a React Native (Expo) application using the fetch method

I am experiencing issues with receiving data on the server side, specifically with image upload functionality. Despite trying various methods, the image folder remains empty when using multer middleware. Here is a snippet of my code: Displaying an Image: ...

Unable to transmit JSON data through FETCH protocol

I have set up an API Service using node js on port 3001 and a web UI with REACT running on port 3000. My goal is to POST details in JSON format from the web page to the API. While I can successfully hit the API, the JSON data is not being received properly ...

A blank screen of errors pops up when attempting to update through a form

Encountering a white error screen when attempting to add an item using a form in Python / Django. I'm currently debugging the issue but lacking information. Any guidance on where to look next would be greatly appreciated. Models.py from __future__ i ...

Using Node.js and Angular to Access Google Spreadsheet JSON Data Across Different Origins

Seeking to extract JSON data from a public Google Spreadsheets page, my initial attempt involved an AJAX call which successfully retrieved the data but I struggled with saving it to my $scope. Switching to $http.get led me to encounter cross-origin reques ...

a tutorial on linking component data to a prop value

Is there a way to connect the searchString value in my Vue component to the item value in the html template it uses? I need to pass this value to the method called in my Ajax request. Vue: Vue.component('user-container-component', { props: ...

Tips for preventing the need to create a function within a loop

Currently, I am in the process of collecting data through REST calls. I have created a function that accesses a "directory" endpoint to retrieve a list of individuals. While I can easily obtain details about their children, I need to make individual AP ...

Leveraging Firebase Dynamic Links through JavaScript

Currently exploring options for implementing Dynamic Links. Firebase Dynamic Links seem promising, but the lack of support for Cordova/ ionic apps is concerning. Is there any plan to add this in the future? Are there any other alternatives that you would ...

Incorporating mootools scripts into a gwt application

My issue involves creating an animation on a Composite that should start when data is loading. To test this, I created animations on regular divs using HTML: <div class="LoadDataWidget"> <div id="arrow" class="greenArrow"></div> < ...

Upon reloading, Nextjs static build automatically redirects users to the homepage

After creating a static Next.js build using npm run export, I encountered an issue while deploying the build on S3 or any other web server such as Apache with .htaccess or Nginx. When accessing the routes by pasting them directly into the browser, they wou ...

The width:auto attribute for images in ie6 is not functioning as expected

I am facing a challenge with dynamically changing and resizing an image element to fit its container. My current approach involves: Resetting the image: // Ensuring the 'load' event is re-triggered img.src = ""; // Resetting dimensions img. ...

Encountering issues accessing / Error within MEAN stack application

I recently completed the Heroku tutorial, which you can find here. I followed all the steps but did not deploy to the Heroku server and instead worked on my localhost. However, when I tried to access my application using localhost port 8080, I encountered ...

Securing the connection between clients and servers through encryption

For my mobile client, I am using Xamarin, with node.js as my backend and MongoDB as the database. The main issue I am facing is how to securely store user data in the database. If I only do server-side encryption, there is a risk of hackers intercepting th ...

Troubleshooting a JavaScript error while attempting to execute a function from a

I have been working on a new JavaScript library named TechX. Check out the code snippet below: (function(){ function tex(s){ return new tex.init(s); }; //initiate the init selector function tex.init = function(s ...

Execute sequential animations on numerous elements without using timeouts

I'm currently working on developing a code learning application that allows users to write code for creating games and animations, similar to scratch but not block-based. I've provided users with a set of commands that they can use in any order t ...

Internet Explorer causing problems with JQuery

I encountered an error with the following code snippet: jQuery.post('/user/result/generate',{ 'id': getHidden() }, function(html) { $('#result').html(html); }); The error message is: ...

Creating new collections automatically in MongoDB using Mongoose when saving a document

Program overview: One of my programs is designed to handle a post request (request) that contains details about a "hometask" including its name, description, importance, and group. It is crucial for the provided group parameter to be recognized as the name ...

Divide the inner HTML content to extract text for translation purposes using JavaScript

I am currently developing an application that requires extracting the innerHTML of Body, then extracting the text in a JSON format. This JSON will be used for translation, and the translated JSON will be used as input to recreate the HTML markup with trans ...

Retrieve the initial data of the AngularJS model upon button click

Previously, I was able to retrieve the initial values of the model using this.model.changed or this.model._previousAttributes in BackboneJS. Now, I am looking to achieve the same functionality in AngularJS, where I can track all changes made to the model ...