Leff
Leff

Reputation: 1298

Javascript - getting TypeError is not iterable for an array

I am using react and I have a component where I am setting a constant with an array of strings:

const propsToCheck = ['text', 'type', 'status', 'topic.name', 'class.0.code'];

I am sending down the children chain all the way to the component that is using it like this in the function checkObjectContainsValue that I import from another file:

constructor(props) {
    super(props);
    this.state.data = this.transformRows(props.rows.filter(obj => checkObjectContainsValue(obj, props.searchString)(props.propsToCheck)))
  }

My tests are failing then because I get an error:

TypeError: propsToCheck is not iterable

But, I noticed that if I import the checkObjectContainsValue function to a parent component where I have propsToCheck I don't get the error. But I can't have that function there for other reasons. I have checked the react developer tools and I can see that I am getting the array propsToCheck in the child component, so I am not sure why I am getting this error?

This is the function checkObjectContainsValue:

const checkObjectContainsValue = (obj, value) => (propsToCheck) => {
  for (let prop of propsToCheck) {
    const propToCheckValue = prop.split('.').reduce((currentObject,property) => {
      return currentObject[property];
    }, obj);
    if (propToCheckValue.toLowerCase().includes(value.toLowerCase())) {
      return true;
    }
  }
  return false;
};

Update

If I move the logic to a parent component then everything works fine. This is the example:

onSearchChange(event) {
    const searchString = event.target.value;
    this.setState(prevState => {
      const filteredTasks = prevState.tasks.filter(obj => checkObjectContainsValue(obj, searchString)(propsToCheck));
      return {filteredTasks: filteredTasks};
    });
  }

Why am I getting this error only when I use this function in the child component?

Upvotes: 0

Views: 9020

Answers (1)

Code Maniac
Code Maniac

Reputation: 37755

Your function expects three argument

const checkObjectContainsValue = (obj, value, propsToCheck) => {

where as you're just passing two argument to function

props.rows.filter(obj => checkObjectContainsValue(obj, props.searchString)

so the third argument will have a value equal to undefined which is not iterable

Upvotes: 1

Related Questions