'React executing code before the previous function call has finished

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);
  }
}


Solution 1:[1]

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
          });
        });
    }
    

Solution 2:[2]

  1. Make your AddNewMember async

  2. const nextId = await maxIDFetch();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Drew Reese
Solution 2 Gurzoni