What are some ways to delay the response time of my Express server in order to accommodate the functionality of the react-admin getOne() method?

I've implemented VetCreate and VetEdit functions to handle creating and editing records in my application. The issue I'm facing is that although the creation response is successful, the new record's ID is not populated when trying to fetch it.

Even though I have used async/await keywords where necessary, the console logs indicate that something is amiss. Surprisingly, if I attempt to edit a record after returning to the list screen, the API works as expected and returns the updated details.

I've included all the relevant code snippets and screenshots, but if you need more information, feel free to ask.

VetCreate
export const VetCreate = (props) => (
  <Create title="Credit Application" aside={<CreateAside />} {...props}>
    <TabbedForm toolbar={<VetCreateToolbar />} redirect="show">
      <FormTab label="applicant">
        // Form fields go here...
      </FormTab>
      <FormTab label="bureau">
        // Bureau related form fields go here...
      </FormTab>
    </TabbedForm>
  </Create>
);

VetEdit
export const VetEdit = props => {
  // Edit component code goes here...
};

DataProvider.js
// Data provider logic goes here...

Vet API
Vet.createVet = async function(newVet, result) {
  // Logic for creating a vet record goes here...
};

Vet.getVetById = async function(VetId, result) {
  // Logic for fetching a vet record by ID goes here...
};

https://i.stack.imgur.com/YbrN2.png

https://i.stack.imgur.com/lpaSP.png

Answer №1

The use of await is only effective when waiting for a promise to resolve. For example, the following code snippet:

await sql.query("INSERT INTO vets set ?", newVet, function(err, res) {...});

does not involve awaiting a promise. This query does not return a promise. The data from this operation is only available in the callback, not through any returned promise. Therefore, await will not have any effect here. There is no intrinsic mechanism in await that recognizes when the regular callback has completed. Without a promise to await, await essentially does nothing (it does not wait for anything).

Instead, it is necessary to utilize database operations that do not rely on callbacks but instead return promises if you intend to use await.

For those using mysql, consider utilizing the promise support provided by mysql2 and adjusting all database statements to leverage the returned promise for processing results, rather than passing a plain callback to the database call.

Answer №2

If you come across this issue and need more insight into the promise - async/await connection, I stumbled upon this helpful article.

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

What is the best method for circumventing an express middleware?

I am currently working on an express application that utilizes several express routes, such as server.get('*' , ... ) to handle common operations like authentication, validation, and more. These routes also add extra information to the respon ...

Struggling with getting React to successfully fetch data from an Express API. Any suggestions on how

I am having trouble with my fetch call to the express API. Even though I receive a response status of 200, I am still getting the index.html instead of the JSON data I need. Here is an overview of my setup: package.json "version": "1.0.0&qu ...

What is the purpose of the .default() method being added to the class constructor in transpiled Typescript code

In TypeScript, I have the following code snippet to create an instance of ConnectRoles Middleware in Express: let user = new ConnectRoles(config); The middleware initialization is expected to be a simple call to a constructor. However, after transpiling, ...

What is the best location to manage errors within a sequelize ORM query?

I am working with the Sequelize ORM within a Node/Express environment. My database has two tables: one for Users and another for Items. The Item table includes a foreign key that is linked to the UserId in the User table. Whenever I attempt to create an ...

I wonder what the outcome would be if I used res.send to send a JSON file instead of res.json

Is it possible to send a JSON file using res.send in NodeJs instead of res.json? What are the potential consequences of doing this and why is it recommended to avoid this practice? ...

How does the execution of app.set('view engine','ejs') work internally in Express?

I am curious about the app.set() method and how it is used to set a value for a name. Currently, I understand that app.get() can retrieve the value by name. However, if I were to set 'view engine' to 'ejs', where exactly does the app.ge ...

Node.js and Express: tackling the problem of duplicate variables

I have a checkUser middleware that saves the user information when a JWT is verified. However, when I integrate it into my routes and attempt to log res.locals.user.username, the username appears twice in the console. This duplication is causing issues wit ...

The Node.js Express Server runs perfectly on my own machine, but encounters issues when deployed to another server

I've encountered a strange issue. My node.js server runs perfectly fine on my local machine, but when I SSH into a digital ocean server and try to run it there, I get this error. I used flightplan to transfer the files to the new machine. deploy@myse ...

Running nodejs scripts within my HTML and JavaScript code

Using express, I send an HTML file to incoming GET requests: app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/public/index.html')); }); Within that HTML file, I included another JavaScript file, script.js, us ...

The function _this2.setState does not work properly in asynchronous situations within React

I have an onChange handler that triggers a Promise Resolve function. This function fetches data array using "PromiseValue", and I use ".then( result )" to retrieve the array field. It works when I print "result" with console.log. However, the issue arises ...

Issues arise when using res.send() with ExpressJS and Mongoose

Initially, I have multiple callbacks that need to be executed before sending a res.send() to construct a JSON API: app.get('/api', function (req, res){ ... function logPagesId() { console.log("load: " +pagesId); c ...

Encountering a problem with the node.js version while trying to install

Currently in the process of setting up my Raspberry Pi as a node.js server. Recently performed a clean installation of Raspberian Subsequently, I installed node Upon running node -v, the system displays: v0.10.25 Proceeded to install npm When checking ...

Starting node.js express server with a delay implemented

Currently, I am utilizing Express for my http server. My aim is to set up the database connection before initiating any HTTP connections from the client side. A snippet of the code is shown below: function connect_to_db(connection_string) {...}; connect_ ...

The Node.js application is up and running on the Node server, but unfortunately, no output is

Greetings, I am a beginner in nodejs. var io = require('socket.io').listen(server); users = []; connections = []; server.listen(process.env.PORT || 3000); console.log('server running....on Pro'); app.get ('/', function(re ...

The use of "app.use("*") appears to be triggering the function repeatedly

app.use("*", topUsers) is being invoked multiple times. The function topUsers is called repeatedly. function topUsers(req, res, next){ console.log("req.url", req.url) findMostUsefullReviewsAggregate(6) .then(function(aggregationResult){ ...

Pass on Redis Pub/Sub messages to a designated client in socket.io through an Express server

Currently, in my express server setup, I am utilizing socket.io and Redis pubsub. The process involves the server subscribing to a Redis message channel and then forwarding any incoming Redis messages to a specific WebSocket client whenever a new message i ...

Creating a JSON tree using MongoDB data in a Node.js environment

There are numerous questions similar to mine, but unfortunately, none seem to fit my specific case. The closest one I found is Create a JSON tree in Node.Js from MongoDB, but it still doesn't quite work as expected. Perhaps this problem is just too ...

What benefits come from installing modules such as socket.io/express globally?

Furthermore, I would like to explore the possibility of executing them from the /usr/local/lib directory instead of having to install these modules in the individual folders of each project I am currently managing. ...

What is causing the issue with Firebase not functioning on my Node.js server?

After reviewing the code below, I encountered an issue: var email = req.body.correo; var pass = req.body.pass; var firebase = require("firebase-admin"); var serviceAccount = require("./prueba-064cb79dba28.json"); firebase.initializeApp({ credential: fire ...

What is the purpose of the Express 4 namespace parameter?

Having worked extensively with Express 4, I recently attempted to implement a namespaced route with a parameter. This would involve routes like: /:username/shows /:username/shows/:showname/episodes I figured this scenario was ideal for express namespacin ...