So I have this line of code:
const { semesters, isLoading } = useSelector((state) => state.semester);
The semesters
object looks like this.
[
{
"isActive": true,
"_id": "617aa8a3f2a712242c272d96",
"acadYear": "A.Y. 2021- 2022, 2nd term",
"__v": 0
},
{
"isActive": false,
"_id": "617aa91aa8f2aa2bc86422e9",
"acadYear": "A.Y. 2025-2026, qweqwe",
"__v": 0
}
]
And I'm trying to perform filter/find function in that array with this code.
const filtered = semesters.filter(sem => sem.isActive !== false)[0].acadYear;
or
const getFind = semesters.find(sem => sem.isActive !== false).acadYear;
Neither works for me and the error I'm getting is that both of the function is undefined. I've tried removing it and got no error. However, when I try to undo it and once it has already been loaded, then it will work. The problem is that when I go back to the page, the error will happen again. Anyone can help me? Thanks in advance.
CodePudding user response:
This happens because upon the very first render, the "semester" object is not yet available inside the redux store.
What you can do is use the optional chaining operator ?
, so that JavaScript checks if the object exists before attempting to run the chained function:
const filtered = semesters?.filter(sem => sem.isActive !== false)[0].acadYear;
This will return undefined
and prevent the error. Once the store object is available, your .filter
and .find
functions will run accordingly.
There are other workarounds. I just find this one to be the one that better suits my needs in most cases.
CodePudding user response:
Because you are using the useSelector
to pull values from Redux, ensure that the default value of semesters
is an empty array not undefined (initializing the default values).
Redux Docs: Initializing State
Alternatively, you can handle this at execution using optional chaining operator:
const firstNotActive = semesters?.find(sem => sem.isActive !== false)?.acadYear;