Using a Get request may not retrieve the most recent data that was added through a Post request

I've added some data using a Post request and now I'm trying to retrieve all the data from the table using a Get request. However, it seems that the last data I added is not being included in the response. Is there a specific approach I should take to ensure I get the updated data?

Below is the code snippet from my controller:

app.ajoutProjet = function () {
  // Add a new project using the CreatProjet() service that utilizes Post method
  Projet.createProjet(app.ajoutData);
  // Retrieve all projects
  Projet.getProjet().then(function(result){
    for(var i=0; i<result.data.projetsListe.length; i++){                      
      // Check if the project name matches the one we just added
      if(result.data.projetsListe[i].NomProjet == app.ajoutData.NomProjet){
        app.ajoutData.projet_id = result.data.projetsListe[i].IdProjet;
        CP.createCP(app.ajoutData);
      }
    }
  }); 
  app.successMsg = 'Project added...Redirection';

EDIT:

Here is the Project Service code:

// Create a new project
createProjet: function (ajoutData) {
  return $http.post('/api/projets', ajoutData);
},

// Retrieve all projects
getProjet: function () {
  return $http.get('/api/projets');
}

Although the project is successfully created, it is not being included in the list of projects returned by the Get request. Any suggestions?

EDIT

Details of my Post method:

router.post('/projets', function(req, res){
  projet.Projet.sync({force: false}).then(function () {
    // Table created
    return projet.Projet.create({
      IdProjet: req.body.IdProjet,
      NomProjet: req.body.NomProjet,
      ResponsableApitech: req.body.ResponsableApitech,
      ResponsableClient: req.body.ResponsableClient,
      client_id: req.body.client_id,
      estArchive: req.body.estArchive
    });

  });
});

Answer №1

When making a get request before the post request has completed processing, you will encounter this issue. It is important to wait for the post request to finish before initiating the get request. To handle this situation, you can implement a promise chain.

Projet.createProjet(app.ajoutData).then(function(response){
  return Projet.getProjet();
})
.then(function(result){
  for(var i=0;i<result.data.projetsListe.length;i++){                      
      //Check if the project name matches the one we just added
    if(result.data.projetsListe[i].NomProjet==app.ajoutData.NomProjet){
      app.ajoutData.projet_id=result.data.projetsListe[i].IdProjet;
      CP.createCP(app.ajoutData);
     }
   }
}); 

Answer №2

The issue stemmed from the post method where there was a lack of error checking even though the project was successfully created. As a result, any code within the

 Projet.createProjet(app.ajoutData).then(function(response){//code})
did not execute. Here is the revised version:

router.post('/projets', function(req, res){
  projet.Projet.sync({force: false}).then(function () {
    // Table created
    return projet.Projet.create({
      IdProjet: req.body.IdProjet,
      NomProjet: req.body.NomProjet,
      ResponsableApitech: req.body.ResponsableApitech,
      ResponsableClient: req.body.ResponsableClient,
      client_id: req.body.client_id,
      estArchive: req.body.estArchive
    }).then(function(projet) {
      if (!projet) {
        res.json({ success: false, message: 'Projet non ajouté' });
      } else {
        res.json({ success: true, message: 'Projet ajouté', projet: projet });
      }
    });
  });
});

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

Angular is the best method for properly loading a webpage

Struggling to solve this issue. I have a webpage where I need to load another webpage, specifically a page from a different site, into a div. Essentially, it's like a news ticker that I want to showcase. The problem is that the URL is stored in a Mon ...

What is the reason for both the d3 line chart and bar chart being shown simultaneously?

On my website, I have implemented both a d3 bar chart and a line chart. You can view examples of them here: line_chart and bar_chart. However, in certain situations only one of the charts is displaying instead of both. Can anyone provide guidance on how ...

What is the best way to implement window.load in React Native?

I'm encountering an issue with a simple button on my page in Expo/React Native. When I try to navigate to a new page using window.open upon clicking the button, I receive an error message saying "undefined is not a function." Although I am utilizing ...

Organize AngularJS ng-repeat using dictionary information

I'm dealing with a dictionary consisting of key-value pairs, which looks something like this: data = { "key1": 1000, "key2": 2000, "key3": 500 } My goal is to display this data in a table using AngularJS. One way I can achieve this is b ...

Is it a scope issue if ng-click is not firing and the function is not working properly?

I'm facing an issue with an animation that is not working as intended. The goal is to have the search button trigger an animation to pull a search bar from the right side, allowing users to input their search query. However, the ng-click function does ...

What could be causing the slow loading time of my Shopify App developed using Next.js (React)?

I recently followed a tutorial at However, I am facing severe performance issues with my app. It loads extremely slowly when changing tabs, whether it's running on ngrok, localhost, or deployed on app engine. I'm new to React, Next.js, and Shop ...

Enzyme in Action: Using React.js to Emulate a Click Event

I have been working on a React.js application which is a straightforward Cart app. You can take a look at the code sandbox here: https://codesandbox.io/s/znvk4p70xl The issue I'm facing is with unit testing the state of the application using Jest and ...

The onClick event is not functioning properly with React's select and option elements

Looking for a way to get the option value from each region? const region = ['Africa','America','Asia','Europe','Oceania']; <div className="options"> <select> ...

Resetting Tabs in Child Component using React

Imagine having two intricate React components developed in TypeScript where one acts as a child component of the other. This child component consists of tabs and keeps track of its own state to determine which tab is currently selected: export const Clien ...

Remove duplicate JSON records in JavaScript by comparing and filtering based on identical attributes

Looking to remove duplicates from a JSON object [{id:1,name:a, cat:1},{id:1, name:a, cat:2},{id:2, name:b, cat:8}] I want to keep only the first occurrence of each duplicated id [{id:1,name:a, cat:1},{id:2, name:b, cat:8}] ...

Passing Props in Material-UI v5xx with ReactJS: A Beginner's Guide

Struggling with the fact that useStyle() isn't functioning properly in my material-UI v5xx version, I found myself at a loss on how to pass props in this updated edition. In Material-UI v4, it was as simple as: const Navbar = () => { const [open ...

Before displaying the rows stored in the controller, ng-repeat initially displays one row

I am experiencing an issue with my back end service sending data to a $scope variable. I am using this variable to populate rows in a table with ng-repeat. Upon loading the page, initially one row is visible on the browser but then disappears once the loa ...

Filtering in JavaScript arrays based on conditions that are not related to the elements in the array

Consider the following code snippet: var numbersArray = [1, 3, 6, 8, 11]; var returnedArray = numbersArray.filter(function(number) { const condition = false // or true sometimes return number > 7 && condition ; }); console.log(returnedArra ...

Troubleshooting Karate - jbang.execute() (Node npm)

Need help with a question that's part of our project presentation. We are working on controlling the output of KARATE, ensuring it returns an OK or a KO depending on the test result. Currently, it always gives back 0 regardless of success or failure. ...

angularJS editable input field with click-to-exit functionality

One issue I encountered involved an editable text field directive in Angular, which is structured like this: myApp.directive('editable', function () { return { restrict: 'E', scope: { model: '=&apos ...

Ways to show a child's component element within the parent container

Within my Angular 11 project, there exists a component that exhibits a child component containing assorted table filters: Parent Component <table-filters></table-filters> <table> ... </table> Child Component (table-filters) <f ...

What steps do I need to take to extract the date and month from a single datepicker using the code below?

<div class="col-md-3 pull-left" style="padding:9px"> <input type="text" id="datepicker" class="form-control"> </div> The HTML and C ...

Is there a CSS3 Selector With Similar Functionality to jQuery's .click()?

For a few years now, I have been utilizing a pure CSS navigation system. However, with the recent increase in mobile site projects at my workplace, I am encountering issues with drop-down menus not functioning properly on mobile devices. Despite this chall ...

The object's texture is not displaying

Seeking Assistance I am a beginner in the realm of Three.js and I am attempting to apply a texture to an imported object. The Issue at Hand Despite numerous attempts, I have been unable to successfully achieve this task. I encounter no errors, but the o ...

Configure unique headers for various environments

I am looking to customize headers like "id", "env", and "name" based on different environments in my application. Each environment has a unique set of values for these headers. I am struggling to implement this effectively within my existing code logic. T ...