0

I have spring boot app for "backend" in order to retrieve data for stocks from yahoo.finance. I have tested the app with postman and retrieves the data. However, I can't make the React ui to present them and the error that I get is 'TypeError: stocks.map is not a function '. My React class:

import { React, useEffect, useState } from 'react';

export const StockPage = () => {

    const [stocks, setStocks] = useState({});

    useEffect(
        () => {
            const fetchStockData = async () => {
                const response = await fetch("http://localhost:8080/stock/AAPL/2021-06-07/2021-06-11");
                const stockData = await response.json();
                setStocks(stockData)
                console.log(stockData);
            };
            fetchStockData();
        },[]
    );

  return (
    <div className="StockPage">
        <h2>Stock Data</h2>
        <div className="header-section">
            {stocks.map(stock => <p>{stock.date} {stock.open} {stock.high} {stock.low} {stock.close} {stock.adjClose} {stock.volume}</p>)}
        </div>
    </div>
  );
}

Also, the console.log(stockData) prints out the array of stock object in browser console.

1 Answer 1

2

Look at your state initialization.

const [stocks, setStocks] = useState({});

You're setting the initial state to an object, not an array. You need

const [stocks, setStocks] = useState([]);

assuming that the API will give you an array in response.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.