Home > Software design >  React executing code before the previous function call has finished
React executing code before the previous function call has finished

Time:05-13

I'm trying to write a record to a database but need to find the next Id in the sequence. I wrote a function to find the highest Id number in the database, increment it and return it.

The calling function then uses that to write the new record. Problem is that it is calling the write function before the maxIDFetch function has completed and returned the variable.

I've tried loads of different combinations but I can't get it to work. Please help

Calling function

function AddNewMember({forename,surname}) {
    const nextId=maxIDFetch();
      writePlayer(true, {
      id: nextId,
      id: uuidV4(),
      forename
    });
  }

maxIDFetch function

import { useState, useEffect } from "react";
import setNewMember from "../App";
import writeMax from "./writeMax";

const CosmosClient = require("@azure/cosmos").CosmosClient;
const configMemberIDConnection = require("../configMemberIDConnection");
const dbContext = require("../contexts/databaseContext");

export default async function maxIDFetch() {
  const { endpoint, key, databaseId, containerId } = configMemberIDConnection;
  const client = new CosmosClient({ endpoint, key });
  const database = client.database(databaseId);
  const container = database.container(containerId);

  try {

    const querySpec = {
      query: "SELECT VALUE MAX(c.memberidnum) from c",
    };

    const { resources: items } = await client
      .database(databaseId)
      .container(containerId)
      .items.query(querySpec)
      .fetchAll();

    let newMax = Number(items)   1;
    writeMax(newMax);
    return newMax;
    //  console.log(items);
  } catch (err) {
    console.log(err.message);
  }
}

CodePudding user response:

  1. Make your AddNewMember async

  2. const nextId = await maxIDFetch();

CodePudding user response:

The maxIDFetch utility function is declared async so it implicitly returns a Promise object. Any callers should wait for the returned Promise to resolve.

  • Declare AddNewMember async and await the returned Promise from maxIDFetch to resolve.

    async function AddNewMember({ forename, surname }) {
      const nextId = await maxIDFetch();
      writePlayer(true, {
        id: nextId,
        forename
      });
    }
    
  • Chain from the returned Promise from maxIDFetch.

    function AddNewMember({ forename, surname }) {
      maxIDFetch()
        .then((nextId) => {
          writePlayer(true, {
            id: nextId,
            forename
          });
        });
    }
    
  • Related