It works for the first click, but when i click it again to unselect it, it shows me error :
state.selectedStudents.includes is not a function. (In 'state.selectedStudents.includes(action.item)', 'state.selectedStudents.includes' is undefined)
import {
SELECT
} from "../actions/postActionTypes";
const initialState = {
students: ['Aditya', 'Rohan', 'Hello'],
selectedStudents: []
}
const selectReducer = (state = initialState, action) => {
switch (action.type) {
case SELECT:
return {
...state,
selectedStudents: state.selectedStudents.includes(action.item) ? state.selectedStudents.splice(state.selectedStudents.indexOf(action.item), 1) : state.selectedStudents.push(action.item)
}
default:
return state;
}
}
export default selectReducer;
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
includes() You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
The "some is not a function" error occurs when the some() method is called on a value that is not an array. To solve the error, convert the value to an array before calling the method or make sure to only call the some() method on valid arrays. Here is an example of how the error occurs.
The simple answer is yes you can place function in an array. In fact, can declare variables and reference them in your function.
First of all state.selectedStudents.includes is not a function.
means that state.selectedStudents
is not an array. so what is it?
.push()
doesn't return the array, it returns the length of the array after push. based on MDN:
Array.push() return value: The new
length
property of the object upon which the method was called.
So after the first SELECT
action, your state chages to this:
state = {
students: ['Aditya', 'Rohan', 'Hello'],
selectedStudents: 1, // <- it's a number, not an array.
}
And the second time you fire SELECT
action, state.selectedStudents.includes(action.item)
throws and error because state.selectedStudents
is 1
which isn't an array.
Change your switch case to this:
switch (action.type) {
case SELECT:
return {
...state,
selectedStudents: state.selectedStudents.includes(action.item) ?
state.selectedStudents.filter(student => student.id !== action.item.id) :
[...state.selectedStudents, action.item] // <- no mutation, creates a new array.
}
default:
return state;
}
state.selectedStudents.push(action.item)
returns the new length of the array and is not a list. so the next time you try it the type number does not have the includes method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With