array.forEach() only returning one element

In my function I use array.forEach to sort through an array however it only returns on element. here’s my code:

import React, {useState, useEffect} from "react";
import axios from "axios";

function Fact(props) {
    const width = 18;
    return (
        <div class="card" style={{width: width + 'rem'}}>
            <div class="card-body">
                <h5 class="card-title">Fact number: {props.id}</h5>
                <p class="card-text">{props.fact}</p>
            </div>
        </div>
    )
}

function UserFacts(props) {

    const email = props.email;

    const [fact, setFact] = useState("");
    const [id, setID] = useState("");

    function getFact() {
        axios.get("https://exampleapi/userfacts?email=" + email + "",  { crossdomain: true }).then(response => {
            const array = response.data
            array.forEach(element => setFact(JSON.stringify(element.fact)));
            array.forEach(element => setID(JSON.stringify(element.id)));
        });
    }

    useEffect(() => {
        getFact();
      }, []);

    return (
        <Fact id={id} fact={fact} />
    )
}

export default UserFacts;

Answer

There’s a couple of things wrong here:

Your hooks only store 1 value so the loop will replace that value each iteration.

I’d recommend making your states arrays like so:

const [facts, setFacts] = useState([]);

const [ids, setIds] = useState([]);

And then when getting those values just push to the state:

axios.get("https://exampleapi/userfacts?email=" + email + "",  { crossdomain: true }).then(response => {
 const array = response.data
 array.forEach(element => facts.push(JSON.stringify(element.fact)));
 array.forEach(element => ids.push(JSON.stringify(element.id)));
});

You are only ever returning 1 fact component, you’ll need to loop through your arrays over the component to generate more than 1

return (
   {facts.map((fact, i) => {
      return <Fact id={ids[i]} fact={fact} />
   }}
)

I’ve kept true to your approach but you might want to consider having one state which stores an array of Fact objects which would have the fact and the id together as I feel this generally reads better when looping over the jsx.