Rohit Verma
Rohit Verma

Reputation: 3785

How to store multiple values in useState of API response?

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?

Upvotes: 0

Views: 114

Answers (2)

mikenlanggio
mikenlanggio

Reputation: 1137

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

Upvotes: 1

vighnesh153
vighnesh153

Reputation: 5388

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.

Upvotes: 2

Related Questions