T
T
tron212021-08-24 17:43:04
React
tron21, 2021-08-24 17:43:04

What is the correct way to loop through an array and add the result to the state variable?

Good day to all! There was a problem adding an array element to the state hook. I'm looping through the array with forEach. If I enter a specific word from the array, then everything works and is added as it should. If I write just one letter (letter a as an example), then only one array element is added, although through console.log I see that there are 15 matches (and there should be 17. All array elements have this letter). I can't figure out where I went wrong. Is the problem in the if construct or somewhere else? Thank you in advance for your help!

This is the function code that is being used. In the handleStartSearch(data) function, data is just a string from the input. dataJson.result is an array of objects.

const [cards, setCards] = React.useState([]);

  function handleStartSearch(data) {
    
    dataJson.result.forEach(item => {

      if ( data.length > 0 && (item.title.includes(data) || item.author_lastName.includes(data)
           || item.author_firstName.includes(data))) {
        setCards([...cards, item])
        console.log('Есть совпадение!');
      }
    })
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-08-24
@timofeus91

function handleStartSearch(data) {
    setCards(!data ? dataJson.result : dataJson.result.filter(item =>
            (item.title.includes(data) || item.author_lastName.includes(data)
           || item.author_firstName.includes(data)))
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question