Answer the question
In order to leave comments, you need to log in
How to overwrite useState([]) from 1 time?
Good day to all. Continuation of my previous question. I'm doing an assignment in React. There is a function that adds sorted data to the array for rendering cards, and in the same function there is a check to change the text. The rendering happens correctly, but the array itself in const [cards, setCards] is overwritten only if the search button is pressed 2 times. From 1 time the array remains the same as it was and because of this the text does not change correctly. At the same time, the data parameter must be passed to the function (this is a regular string from the search input). Tell me, please, what have I missed?
const [cards, setCards] = React.useState([]);
const [inputValue, setInputValue] = React.useState('Поиск');
function handleStartSearch(data) {
setCards(!data ? [] : dataJson.result.filter(item =>
(item.title.includes(data) || item.author_lastName.includes(data)
|| item.author_firstName.includes(data)))
)
console.log(cards);
if(cards.length > 0) {
setInputValue(`По вашему запросу '${data}' мы нашли`)
}
else {
setInputValue(`По вашему запросу '${data}' мы ничего не нашли`)
}
}
Answer the question
In order to leave comments, you need to log in
In React, the setstate operation is not synchronous, meaning that the result of applying setCards will only be visible when the component is rerendered. If you want to get the changed cards array, then you need to either create a temporary variable for this data and then pass it to setCards:
const computedCards = // выражение, которое вы кладёте в setCatds
setCards (computedCards);
console.log(computedCards);
React.useEffect(() => {
console.log(cards);
}, [cards]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question