Reputation: 369
I am trying to make the search bar when the searchQuery === ""
the user list will be clear and the data will disappear if I clear all the word in input.
Here is my following code:
const Invitees = (props) => {
const [searchQuery, setSearchQuery] = useState("");
const [invitees, setInvitees] = useState([]);
const handleChange = (event) => {
event.preventDefault();
setSearchQuery(event.target.value);
};
const handleSubmit = async () => {
const res = await axios.get(`/api/v1/search/users/invite/${searchQuery}`);
setInvitees(res.data[0]);
};
useEffect(() => {
if (searchQuery === "") {
setInvitees([]);
}
}, []);
return (
<div className="invitees-container">
<div className="invitees-wrapper">
<div className="invitees-sortes">
Sort by: <u>Recommended</u>{" "}
<svg
width="12"
height="6"
viewBox="0 0 12 6"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M6 6L0.803848 0L11.1962 0L6 6Z" fill="#A9A9A9" />
</svg>
</div>
<div className="invitees-search">
<Button
className="input invitees--search-icon"
style={{ color: "white", backgroundColor: "#00B790" }}
type="submit"
onClick={handleSubmit}
>
<SearchIcon />
</Button>
<input
className="invitees--search_input"
type="search"
name="name"
onChange={handleChange}
placeholder="Name, Skill, Location"
aria-label="Search bar"
pattern="^[a-zA-Z0-9 ]+"
required
/>
</div>
</div>
<Grid
container
direction="row"
justify="flex-start"
alignItems="stretch"
spacing={6}
>
{invitees.map((user, index) => (
<Grid item className="invitees-card" key={index}>
{user.Memberships.length < 1 && <InviteCard user={user} />}
</Grid>
))}
</Grid>
</div>
);
};
How can I achieve that feature?
Upvotes: 1
Views: 62
Reputation: 21
axios
.get('/api/v1/search/users/invite/${searchQuery}')
.then((res) => res.data)
.then((data) => setInvitees(data[0]));
}, []);
Try that?
I think your axios should be indeed in the useEffect.
And you keep the condition you want in it.
Upvotes: 0
Reputation: 12777
You need to add dependencies in useEffect
:
useEffect(() => {
if (searchQuery === "") {
setInvitees([]);
}
}, [searchQuery ]);
Upvotes: 3
Reputation: 13588
Add a condition in handle change
const handleChange = (event) => {
event.preventDefault();
if (event.target.value === '') {
setInvitees([])
}
setSearchQuery(event.target.value);
};
Upvotes: 2