[英]How can I fetch data with useEffect in react
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.当
searchQuery === ""
用户列表将被清除并且如果我清除输入中的所有单词时数据将消失,我正在尝试制作搜索栏。
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?我怎样才能实现该功能?
You need to add dependencies in useEffect
:您需要在
useEffect
添加依赖项:
useEffect(() => {
if (searchQuery === "") {
setInvitees([]);
}
}, [searchQuery ]);
Add a condition in handle change在句柄更改中添加条件
const handleChange = (event) => {
event.preventDefault();
if (event.target.value === '') {
setInvitees([])
}
setSearchQuery(event.target.value);
};
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.我认为您的 axios 应该确实在 useEffect 中。
And you keep the condition you want in it.你保持你想要的条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.