I am trying to write a component that lists a set of results when clicking the Find button. However when I click the Find button, the results
state variable is not being reset when I call setResults([])
.
Also it does not return each result in the results array, only the latest one. Could I be calling results.map
or result.resultItems.map
incorrectly as well?
This is what I look like when I click the Find button three times:
I need it to look like this, even when clicking the Find button again:
const SearchContact = () => {
const [results, setResults] = useState([]);
const handleFind = () => {
setResults([]);
const response = [
{ name: "Tim", email: "[email protected]" },
{ name: "Fred", email: "[email protected]" }
];
for (var i = 0; i < response.length; i++) {
const resultItems = [];
resultItems.push(<div>{response[i].name}</div>);
resultItems.push(<div>{response[i].email}</div>);
setResults([...results, { resultItems: resultItems }]);
}
}
return (
<Button onClick={handleFind}>Find</Button>
{results.map((result, index) => {
return (
<div key={index}>
{result.resultItems.map((resultItem, index) => {
return <div key={index}>{resultItem}</div>;
})}
</div>
);
})}
)
}
2
Answers
Try tihs:
Simply call
setResults(results)
in the handleFind function, no need to callsetResults([])
, or any of the looping logic, like this:and the in the JSX do: