Reputation: 61
const [list, setlist] = useState([]);
const token = localStorage.getItem("token");
const requestOptions = {
method: "GET",
headers: { authorization: `Bearer ${token}` },
};
useEffect(() => {
fetch("http://localhost:3000/recruiter/postedjobs",requestOptions)
.then((response) => response.json())
.then((data) => {
setlist(data.data);
});
});
I am working on the react js where i have to show the list of user after the page render so i use the useeffect hook what when i write the useeffect hook it call the api infinite time how can stop this. if i add the blank dependencies [] it show requestoptions are missing from dependencies
Upvotes: 2
Views: 471
Reputation: 1041
Pass an empty array as a second argument to useEffect Hook.
useEffect( ()=>{
console.log(‘hello’);
}, [] );
If you would leave the second argument of the Effect Hook empty, you would run into an infinite loop because the Effect Hook always runs after the state has changed. Since the Effect Hook triggers another state change, it will run again and again to increase the count.
Upvotes: 2
Reputation: 884
You sould pass requestOptions as second argument
const [list, setlist] = useState([]);
const token = localStorage.getItem("token");
const requestOptions = {
method: "GET",
headers: { authorization: `Bearer ${token}` },
};
useEffect(() => {
fetch("http://localhost:3000/recruiter/postedjobs",requestOptions)
.then((response) => response.json())
.then((data) => {
setlist(data.data);
}, [requestOptions]);
});
Upvotes: 0