I have a state variable stock_data
having an array of details of all stock. Structure:
{
"scrip_code": 506235,
"short_name": "ALEMBICLTD",
"Ex_date": "12 Sep 2022",
"Purpose": "Dividend - Rs. - 1.8000",
"RD_Date": "13 Sep 2022",
"BCRD_FROM": "",
"BCRD_TO": "",
"ND_START_DATE": "06 Sep 2022",
"ND_END_DATE": "12 Sep 2022",
"payment_date": "",
"exdate": "20220912",
"long_name": "ALEMBIC LTD."
},
I want to filter that data out. I need to add some new key value pairs too (div_or_share
and div_amount
).
My approach was to make a new array variable myNewData
and mapping from state variable stock_data
:
const [stock_data, setStockData] = useState([]);
var myNewData = [];
const makeMyNewData = () => {
console.log("in makeMyNewData with stock_data:", stock_data);
stock_data.map((item) => {
var [first, rest, end] = item.Purpose.split("-");
var newObject = {
short_name: item.short_name,
long_name: item.long_name,
div_or_share: first,
Ex_date: item.Ex_date,
div_amount: isNaN(Number(end))
? "-"
: "Rs. " + Number(end).toFixed(2)
};
console.log("newObject:", newObject);
myNewData.push(newObject);
});
}
const fetch_BSE_Data = () => {
console.log("fetching data");
return fetch(
"https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S"
)
.then((response) => response.json())
.then((data) => setStockData(data))
};
I am fetching the data and storing in stock_data
variable using fetch_BSE_Data()
, but the console.log
below shows that it's empty. So, while calling makeMyNewData()
, stock_data
is empty:
useEffect(() => {
fetch_BSE_Data()
console.log("after fetching stock_data:", stock_data);
makeMyNewData();
setStockData(myNewData);
}, []);
I want to send this updated stock_data
to a child component:
<DividendCalendar stock_data={stock_data} />
How to resolve this?
Also, the props.stock_data
has the original unfiltered data when logged in console, but when I try to initialize a state variable in DividendCalendar
, the div_cal_data
also turns out to be empty by the console log below:
In DividendCalendar
component:
var [div_cal_data, setDivCalData] = useState(props.stock_data);
console.log("div_cal_data", div_cal_data);
Can someone help me with this?