I have button click system and it works.
JavaScript
x
11
11
1
function clickCreate(msg){
2
console.log(msg);
3
}
4
const CreateButton = (props) =>{
5
return(
6
<div>
7
<i onClick = {() => clickCreate("test")} id="createBtn" className="fas fa-5x fa-microphone-alt"></i>
8
</div>
9
);
10
}
11
Now I want to fetch the API inside the function.
So, change the function clickCreate
like this
JavaScript
1
11
11
1
function clickCreate(msg){
2
const [result, setResult] = useState([]);
3
useEffect(() => {
4
axios.get('http://localhost:8000/api/genres/')
5
.then((res)=> {
6
console.log(res.data.items);
7
setResult(res.data.items);
8
}).catch(err=>{console.log(err);});
9
}, []);
10
}
11
However there comes error like this.
I should not use useState and useEffect in function, but how can trigger the API by btn click??
JavaScript
1
6
1
./src/views/Components/Components.js
2
Line 168:31: React Hook "useState" is called in function "clickCreate" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
3
Line 170:3: React Hook "useEffect" is called in function "clickCreate" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
4
5
Search for the keywords to learn more about each error.
6
Advertisement
Answer
You should move the hook to component level (Rules of hooks), then you can fetch on click and use the hook’s setter:
JavaScript
1
27
27
1
const CreateButton = (props) => {
2
const [result, setResult] = useState([]);
3
4
// should be in scope with `setResult`
5
function clickCreate() {
6
axios
7
.get("http://localhost:8000/api/genres/")
8
.then((res) => {
9
console.log(res.data.items);
10
setResult(res.data.items);
11
})
12
.catch((err) => {
13
console.log(err);
14
});
15
}
16
17
return (
18
<div>
19
<i
20
onClick={clickCreate}
21
id="createBtn"
22
className="fas fa-5x fa-microphone-alt"
23
></i>
24
</div>
25
);
26
};
27