Home > Software design >  Looping though state in React for multiple API calls
Looping though state in React for multiple API calls

Time:09-23

I'm trying to loop though a state(market) to perform a fetch call for each element in the state, and store it in another state(marketData). However it returns the following error ":Unhandled Rejection (TypeError): Cannot read property 'state' of undefined"

Any help would be appreciated.

function Market() {

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

const [market, setMarket] = useState(["SPY", "QQQ", "IWM", "DIA"]);
const [marketData, setMarketData] = useState([]);

  const fetchMarketData = async () => {
    const data = await this.state.market.map((market) => {
      return fetch(
        `https://sandbox.iexapis.com/stable/stock/${market}/chart/1m?token=key`
      );
      const marketHistoricalPrice = data.json();
      console.log(marketHistoricalPrice);
      setMarketData(marketHistoricalPrice);
    });
  }

CodePudding user response:

if you're using hooks (useState) then you dont need this.state.market.map, just using market.map should suffice

Change to

const data = await market.map((market) => {

CodePudding user response:

You can use Promise.all:

function Market() {

useEffect(() =>{
    const promises = fetchMarketData();
    Promise.all(promises).then(values => {
      setMarketData(values)
    })
  }, []);

const [market, setMarket] = useState(["SPY", "QQQ", "IWM", "DIA"]);
const [marketData, setMarketData] = useState([]);

const fetchMarketData = () => {
  const data = market.map(async (market) => {
     const res = await fetch(`https://sandbox.iexapis.com/stable/stock/${market}/chart/1m?token=key`)
     return res.json()
  };
}

CodePudding user response:

If you using hooks (useState) don't need this keyword. You can directly access the state value.

 const data = await market.map((market) =>
  • Related