Home > Back-end >  How to store multiple values in useState of api response?
How to store multiple values in useState of api response?

Time:11-04

I'm calling a api with another api like

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 second api two time (it may be more than two) 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?

Thanks for your efrorts!

CodePudding user response:

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

CodePudding user response:

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.

  • Related