Attempting to execute a post request followed by a get request

I need assistance optimizing my code. What I am trying to achieve is to create a user (partner) and upon completion of the post request, fetch all partners from an API. This includes the newly created partner so that I can access their ID to use in subsequent parts of my code.

The PartnerName will be whatever value the user inputs into the form for posting here.

    await axios
      .post(newPartnerUrl, { Name: PartnerName }, options)
      .then(async () => {
        const partnersRes = await axios.get(getPartnersUrl, options);
        const partners: IPartner[] = partnersRes.data;
        partners.map((partner: IPartner) => {
          if (partner.Name === PartnerName) {
            partnerId = partner.Id
          }
        });
      });

    const PartnerId = partnerId

I would appreciate any help or suggestions on improving this code for better efficiency.

Answer №1

My recommendation is to fully utilize the async/await feature instead of mixing it with then. Following that, you can employ the find function to retrieve the most recent partner based on their PartnerName.

async function addPartner() {
    await axios.post(newPartnerUrl, { Name: PartnerName }, options);

    const partnersRes = await axios.get(getPartnersUrl, options);
    const partners: IPartner[] = partnersRes.data;
    //locate the newly added partner
    const newPartner = partners.find((partner: IPartner) => partner.Name === PartnerName);

    const PartnerId = newPartner.id

    //TODO: There are other tasks you can perform with the newly added partner
}

Answer №2

Discovered a solution, it seems that the partner was not being added to the database when the get request was made. I implemented a 2-second timeout to give the partner enough time to be added.

If anyone else is facing this issue, here is the code snippet:

function delay(n){
    return new Promise(function(resolve){
        setTimeout(resolve,n*1000);
    });
}

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

Tips for filtering data using an array within an object containing arrays

Below is the provided information: userRoom = ['rm1']; data = [{ name: 'building 1', building: [{ room: 'rm1', name: 'Room 1' },{ room: 'rm2', name: ' ...

Having trouble with image loading in NextJS after replacing an old image with a new one?

I have been attempting to swap out my current banner with different images to test if they work, but every image I try leads to an error when using next/image or even a simple <image> tag. The error message states that "The requested resource isn&apo ...

Response from Axios occurs once the component has finished rendering

Currently, I have a situation where a parent component is making an Ajax request using Axios. The response from this request gets stored in a variable named 'carousel' and then passed down to the child component. In the child component's &a ...

Merging two arrays of objects from the same response in JavaScript

How can I efficiently merge two arrays of objects from the same response? let data = [{ "testLevel":"mid", "testId":"m-001", "majorCourse": [ { "courseName":"C++" ...

I've encountered some issues with importing pagination from modules after installing SwiperJs

Having some issues with importing pagination from modules in SwiperJs for my nextjs project. The error message "Module not found: Package path ./modules is not exported from package" keeps popping up. I have tried updating the module to the latest version ...

Expanding the Window Object in Typescript with Next.js Version 13

Within my Next.js 13 project, I am looking to enhance the Window object by adding a property called gtag I created an index.d.ts file in the root folder with the following content: index.d.ts declare module '*.svg' { const content: any; exp ...

A comprehensive guide on utilizing the ngFor directive for looping through objects

After trying to iterate over this dataset within my HTML, I attempted a nested ngfor, but unfortunately encountered an error. My attempt involved iterating the object twice with a nested ngfor, resulting in the following error: HabitRecordsComponent.ht ...

What steps can be taken to prevent a child component from re-rendering when the parent updates the context or state in React JS?

How can I prevent a child component from re-rendering when the parent updates the context or state in React JS? I have already implemented React.memo, but the component still re-renders. Below is my child component: const Ab = () => { console.log(&q ...

Is it possible to identify in Next.js whether scrollRestoration was triggered, or if the back button was pressed?

I've been utilizing the scrollRestoration functionality within Next.js to save and restore the page position whenever a user navigates using the back button. However, I've encountered an issue with it not restoring the horizontal scroll position ...

The error message is: "Cannot access property 'up' of an undefined object within the material UI library using theme.breakpoints."

I am encountering difficulties with the export of makeStyles. Below you can find my code and configuration: import SearchField from "../SearchField"; import { TextField, Select, useMediaQuery, Grid, Button, Box, Fade } from '@material-ui/core&ap ...

Implementing the same concept yet yielding diverse variations?

I'm a bit confused as to why a1 is evaluated as false while a2 is considered to be of type boolean. Can someone explain the reasoning behind this discrepancy? type Includes<T extends readonly any[], U> = U extends T[number] ? true : false; type ...

Express middleware generator function causing a type error

I recently implemented a function that takes a middleware function, wraps it in a try-catch block, and then returns the modified middleware function. tryCatch.ts import { Request, Response, NextFunction } from "express"; export default function ...

What is the best method for uploading source maps to Sentry from a Next.js project?

Summary: Deploying a next.js application on Vercel Utilizing sentry.io for error monitoring Struggling with setting up source maps correctly Long Form: Significant changes have occurred since the early versions of Sentry (formerly known as Raven). There ...

Showing text above bars in MUI X BarChart

I am currently utilizing the <BarChart> component from @mui/x-charts (version "^6.19.1") and I am looking to enhance readability by displaying the data values on top of each bar. Current Output: view image description here Desired Outc ...

The state will reset whenever there is a change in values within an object, but this will only occur if I am

What I'm looking to achieve is this: I need to choose a single card view to edit Once editing is done, I want to save the changes Please refer to the video I've uploaded for clarification and can you please explain why this issue is occurring. ...

Tips for omitting the trailing slash from a specific route in Next.js

Having an issue with Next.js Trailing Slash on certain pages. I have implemented a media query like: /example?type=something However, when adding a trailing slash, it becomes: /example/?type=something Is there a way to eliminate the trailing slash on p ...

Implementing onClick functionality to change background color with styled components

Is there a way to apply background color when a user clicks on any page in pagination using React styled components? I was able to achieve this with simple CSS by adding the class ".selected" which had a background-color of red, but now I need to use React ...

Using next.js and redux for user authentication: a step-by-step guide

After creating my next.js app with version 9.3.5, the authentication was working perfectly. However, after updating next-redux-wrapper and next.js, I noticed that when I refresh the page, the user is no longer authenticated even though the cookie still exi ...

What is the best way for me to generate a fresh object?

In one of my components, I have implemented a feature where clicking on an image toggles a boolean variable to show or hide a menu. The HTML structure for this functionality is as follows: <img src="../../assets/image/dropdown.png" class="dropdown-imag ...

If the user is not present in NextJS 13 with authentication context, automatically navigate to the homepage

I am currently working on implementing an authentication system using JWT in my upcoming app. However, I've encountered an issue while dealing with protected pages, specifically my profile page (which is a protected page): 'use client' impor ...