0

I'm calling a API with another API.

First API have list like a labels:

{
    "body": [
        {
            "label": "label one",
            "inputVal": "input value one"
        },
        {
            "label": "label two",
            "inputVal": "input value two"
        }
    ]
}

Second API will validate each label and input as we are using in first API:

So I'm calling the second API at least twice, because I need to validate two label and input as in first API.

const [inputVal, setInputVal] = useState([]);

async function firstApi() {
    axios
      .post('first_api_url', {
        title: "title",
      })
      .then((res) => {
        if (res) {
          res.data.body.forEach((val) => {
            secondApi();
          });
        }
      });
  }

async function secondApi() {
    axios
      .post('second_api_url', {
        titleSecondApi: "titleSecondApi",
      })
      .then((res) => {
       if (res.data.body.msg) {
          setInputVal([res.data.body.msg]);
          console.log(inputVal);
        }
      });
}

Now I'm getting second API response only last response but I need all response in an array.

I'm using inputVal useState for that but not getting all the values in array. How to get it?

1
  • how does the response from second API looks as ? Commented Nov 4, 2022 at 7:08

2 Answers 2

2

Currently, you are over-writing your state with a new array. You need to preserve your previous responses. To do that, you need to update your setter in the second API's then block like the following:

setInputVal(previous => [...previous, res.data.body.msg]);

You can learn more about spreading in javascript arrays here.

Sign up to request clarification or add additional context in comments.

Comments

1

If I got your point correctly, you may try to change your code like that:

const [inputVal, setInputVal] = useState([]);

async function firstApi() {
    axios
      .post('first_api_url', {
        title: "title",
      })
      .then((res) => {
        if (res) {
          res.data.body.forEach((val) => {
            secondApi();
          });
        }
      });
  }

async function secondApi() {
    axios
      .post('second_api_url', {
        titleSecondApi: "titleSecondApi",
      })
      .then((res) => {
       if (res.data.body.msg) {
          setInputVal(prev=> {
            return [...prev, res.data.body.msg]
          });
          console.log(inputVal);
        }
      });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.