Reputation: 33
I am a beginner in react. I'm trying to send values of my database from one file to another using react-hooks, and getting the following error can anyone help me with this?
Line 5:41: React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks Code:
import React, {useState, useEffect} from "react";
import Axios from "axios";
const [collegeList, setcollegeList]=useState([]);
useEffect(()=>{
Axios.get("http://localhost:3001/api/get").then((response)=>{
setcollegeList(response.data);
});
}, []);
CollegeList = collegeList;
export default CollegeList;
Upvotes: 3
Views: 8205
Reputation: 844
Simply move the useState hook into the component. Hooks in react can only be called from the body of the components.
Upvotes: 0
Reputation: 231
You must use react hooks in react components. There're two ways i can recommend to you to fix this.
first) Doing it in your component
import React, {useState, useEffect} from "react";
import Axios from "axios";
function CollegeListComponent() {
const [collegeList, setcollegeList]=useState([]);
useEffect(()=>{
Axios.get("http://localhost:3001/api/get").then((response)=>{
setcollegeList(response.data);
});
}, []);
return "YOUR VIEW ELEMENTS"
second) Use it as react hook
import React, {useState, useEffect} from "react";
import Axios from "axios";
// making a custom react hook like this
function useCollegeList() {
const [collegeList, setcollegeList]=useState([]);
useEffect(()=>{
Axios.get("http://localhost:3001/api/get").then((response)=>{
setcollegeList(response.data);
});
}, []);
return { collegeList }
and then you can import useCollegeList in your component to use it
Upvotes: 3