React Native axios GET method to get all data from subpages and display them

Viewed 162

Hello i'm new with axios and i wanna to display all my data from subpages to screen but I have some trouble because when I display them it shows me the data from the last subpage instead of all of them at the bottom I throw the code how I download the data through axios. How do I display them all ?

const [data, setData] = useState([]);
async function test() {

for (let id = 1; id < 3; id ++) {
        axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`)
            .then(({data}) => {
                setData(data.commentData)
                console.log(data.commentData)
            })
            .catch((error) => console.error(error))
    }
}

useEffect(() => {
    test()
}, []);
1 Answers

You are overwriting your data state in each loop, so the last loop iteration is the one that you see.

async function test() {
  for (let id = 1; id < 3; id++) {
    axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`)
      .then(({ data }) => {
        setData(data.commentData) // <-- overwrites previous state
        console.log(data.commentData)
      })
      .catch((error) => console.error(error));
  }
}

Use a functional state update to correctly update from the previous state.

async function test() {
  setData([]);
  for (let id = 1; id < 3; id++) {
    axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`)
      .then(({ data }) => {
        setData(data => [...data, data.commentData]) // <-- append new data
        console.log(data.commentData)
      })
      .catch((error) => console.error(error));
  }
}

You could also map an array of Promises and use Promise.all to get a single array of resolved data values.

async function test() {
  const requests = [1,2,3].map(id => axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`));
  try {
    const dataArr = await Promise.all(requests);
    setData(dataArr.map(({ data }) => data.commentData));
  } catch(error) {
    console.error(error);
  }
}
Related