I'm trying to filter through an array to pull out all the objects that match a specific month. I've passed the month in from the parent component, and when I console.log(month) it successfully returns 4 in this case.
Here's the beginning of my component:
const MonthlyIncome = ({incomeData, month}) => {
useEffect(()=>{
console.log(month)
//returns 4
console.log('income data', incomeData)
if (month) {
const incomes = incomeData?.filter(i=>{
if(new Date(i?.date).getMonth() === month) {
return i
}})
console.log('incomes', incomes)
}
}, [])
The console.log('incomes', incomes) returns an empty array.
However, I can get it to successfully console.log the filtered array if I input a 4 directly into the useEffect instead of using month, like this:
const MonthlyIncome = ({incomeData, month}) => {
useEffect(()=>{
console.log(month)
//returns 4
console.log('income data', incomeData)
if (month) {
const incomes = incomeData?.filter(i=>{
if(new Date(i?.date).getMonth() === 4) {
return i
}})
console.log('incomes', incomes)
}
}, [])
Does anyone know how I can properly pass in the month from the parent component into the filter() method?
I found a solution, I guess the actual problem was that the number coming from the parent was a string, and I needed it to be an actual number. So I used parseInt() to convert it from a string into a number like this:
const MonthlyIncome = ({incomeData, month}) => {
useEffect(()=>{
console.log(month)
//returns 4
console.log('income data', incomeData)
const m = parseInt(month, 10)
const incomes = incomeData?.filter(i=>{
if(new Date(i?.date).getMonth() === m) {
return i
}})
console.log('incomes', incomes)
}, [])