Oliver D
Oliver D

Reputation: 2889

How to check every item inside array?

I have an array of objects and render every item inside it in input and under this section, I have a button that does something

I want to check every item "input" if it's empty don't call a function pressed on the button

my code works for first object not all,

state

 toolsUsed: [
      {
        id: 0,
        name: '..',
        price: '..',
        count: '..',
      },
      {
        id: 1,
        name: '..',
        price: '..',
        count: '..',
      },
      ...
    ],
]

here's my iterable array

renderToolsUsed = () => {
    const {toolsUsed} = this.state;

    return toolsUsed.map(({name, id, price, count}, i) => {
      console.log('i', i);
      if (
        toolsUsed[i].name.length > 0 &&
        toolsUsed[i].price.length > 0 &&
        toolsUsed[i].count.length > 0
      ) {
        this.setState({valid: true});
      }

      return(
         <View>.....</View>
      )
    }

Button function

 pressed = ()=>{
    if(this.state.vaild){
       call...
    }else{
        alert("please fill all fields");
    }
  }

EDIT

For answer @SLePort

renderToolsUsed = () => {
    const {toolsUsed} = this.state;

    return toolsUsed.map((item, i) => {
      console.log(item);
      this.setState(
        {
          // ...item,
          isValid: ['name', 'price', 'count'].every(
            key => item[key].length > 0,
          ),
        },
        () => console.log('isValid', this.state.isValid),
      );

       return (
        <View key={i} style={styles.tools}>
             <Text>{item.name}</Text>
             ...
        </View>
       );
      });
  };

Upvotes: 0

Views: 143

Answers (2)

SLePort
SLePort

Reputation: 15461

You can loop on the items and add a isValid key if every property to check has a length > 0.

const toolsUsed = [
  {
    id: 0,
    name: 'first',
    price: '2',
    count: '4',
  },
  {
    id: 1,
    name: 'second',
    price: 1,
    count: 8,
  },
]

const validToolsUsed = toolsUsed.map(item => ({
    ...item, 
    isValid: ['name', 'price', 'count']
      .every(key => item[key].length > 0 )
  })
)

Upvotes: 1

Sumanth Madishetty
Sumanth Madishetty

Reputation: 3605

The way you are doing, it set's state for the first item only, After setState is called as it triggers re-render may be you are facing issue may be Array.reduce will help you

try this

 const isValid =  toolsUsed.reduce((acc, curr) => {
  if(curr.name.length && curr.price.length && curr.count.length) {
     return true
   }
   return false
   }, false
   )
this.setState({isValid })

If you have any codesandbox sample please share, so that the function can be optimised, please observe that the second paramenter of the reduce fuction will be the initial value of accumulator acc, may be you have to tweak it for your actual functionality to work

Please feel free to ask questions if any

Upvotes: 0

Related Questions