score:0
useeffect(() => {
const config = {
headers: {
authorization: 'bearer ' + localstorage.getitem('token')
}
}
axios.get('users', config).then((res) => {
if (res.status == 200 && res.data.msg == "success") {
setusers(res.data.users)
}
else {
history.push("/");
}
feather.replace()
});
}, []);
note here i passed the empty array[]
as the second argument for useeffect,
reason of empty array at useeffect
if you want to run an effect and clean it up only once (on the mount and unmount), you can pass an empty array ([]) as a second argument. this tells react that your effect doesn’t depend on any values from props or state, so it never needs to be re-run. this isn’t handled as a special case — it follows directly from how the dependencies array always works.
read more about useeffect
score:0
you would want to add an empty array as useeffect
dependency, so it only run once:
useeffect(() => {
const config = {
headers: {
authorization: "bearer " + localstorage.getitem("token"),
},
};
axios.get("users", config).then((res) => {
if (res.status == 200 && res.data.msg == "success") {
setusers(res.data.users);
} else {
history.push("/");
}
feather.replace();
});
}, []); //<-- add empty dependency here
score:0
the useeffect
hook basically accepts two arguments, the first one being the callback, and the second one is an array of dependencies (optional). the purpose of the second argument (array of dependencies) is to trigger the callback function, whenever any value in the dependencies array change. so, if you don't use the dependencies array in your useeffect
hook, the callback function is executed every time the component is rendered, i.e, whenever the state variables are mutated.
so what's causing the loop?
const [ users, setusers ] = usestate([]);
useeffect(() => {
const config = {
headers: {
authorization: 'bearer ' + localstorage.getitem('token')
}
}
axios.get('users', config).then((res) => {
if (res.status == 200 && res.data.msg == "success") {
setusers(res.data.users) //updating state causes the component to re-render
}
else {
history.push("/");
}
feather.replace()
});
});
looking at your code, we can observe that you are using two hooks ( usestate
and useeffect
) , so when the promise is resolved, you are updating your users
state with the latest fetched information. so far, so good. when a state is updated, we know that the component is re-rendered (that's the basic principle on how react works). so updating the users
state causes the component function to re-render, which would again invoke useeffect
which would again update users
state, and so forth.
workaround
to avoid this loop, we'd want to execute useeffect only once, and not every time the component is rendered. this could be accomplished by passing an empty array as the second argument (which basically tells react to run `useeffect` only when the component is rendered for the first time).const [ users, setusers ] = usestate([]);
useeffect(() => {
const config = {
headers: {
authorization: 'bearer ' + localstorage.getitem('token')
}
}
axios.get('users', config).then((res) => {
if (res.status == 200 && res.data.msg == "success") {
setusers(res.data.users) //updating state causes the component to re-render
}
else {
history.push("/");
}
feather.replace()
});
},[]); //empty array as the second argument
this is similar to componentdidmount
when working with class-based components.
further, you could also add variables to the array that would cause the useeffect
to be invoked only when the variables in the array are mutated.
score:0
add dependency array to you're useeffect hook , this will solve you're problem
this will act like component did mount
useeffect(()=> {
/// you're code
} , [])
but the one that you used acts like component did update and causes problem because you need to execute the code only when component mounted
Source: stackoverflow.com
Related Query
- Reactjs using useState causing loop of axios requests
- reactjs Avoid Infinite loop using the useState and useEffect
- Send array row to row using axios requests in a for loop (One by one)
- Multiple API requests using Axios ReactJS
- Multiple Axios Requests Into ReactJS State
- How to make multiple Axios requests using a dynamic array of links in Javascript?
- ReactJS - Handle POST requests using react router dom
- reactjs make https (not http) requests with axios
- Using Auth0 React Hook on all Axios requests
- Adding a key-value pair to an object inside loop using React useState hook
- React UseState hook causing infinite loop
- Why useState hook don't update while using loop inside useEffect()
- $_FILES is empty when sending a POST request using axios in ReactJs
- Create Chart using Reactjs Chartjs and axios
- Error handling with axios requests in reactjs
- ReactJS useState hook: Can I update array of objects using the state variable itself?
- React useState Causing an infinite loop
- Requests between ReactJS Axios and Go API
- Why do my fetch request causes an infinite error loop in ReactJs using React Toast Notifications
- Send multiple axios requests in a for loop in series (One after the other)
- Infinity loop using useState with useEffect in React
- Can't update state using useState and axios response with array
- Using useState of complex object not working as expected in ReactJS
- How to set cookie with JWT token in ReactJS frontend using Node, Express, Axios
- React axios get request without resulting in infinite loop using useEffect
- Get textarea character count using reactjs with help of usestate hook
- How to manage differents API endpoints in ReactJS using axios
- How to set a state in a forEach loop using useState hook
- How to correctly set state in a loop in react functional component using useState
- Access to XMLHttpRequest blocked by CORS Policy in ReactJS using Axios
More Query from same tag
- How to clear an interval set in this particular way
- Connecting Slate to Formik - is it useField?
- How to render accents in ReactJs?
- jest test for a custom hook
- Display 'No Rows' message after applying filter in MUI DataGrid
- Keypress event handler for a11y compliance
- Array Of Objects from State Returning length 0 when queried, but logging the array shows the proper length
- Unsure of how to trigger useEffect when updating a nested object property in component state
- Why is my ReactJS component state change not triggering a re-render?
- set color to Reactsrap Navlink
- How to set custom headers on Express and receive it on axios
- Why react shows TypeError: undefined has no properties even after passing it properties?
- Merge two JSON data into one with particular key values
- How to align material-ui Grid items vertically centered?
- unable to retrieve the values from the specific thing
- React ref syntax and components as pure functions
- How to get specific mobile device model on webapps using reactjs?
- best way to show a header in map function if condition different to previous item
- Redux state mutation
- API in nodejs Port Issue
- Create a React componenent by grouping an array by index range in JS
- Input field background color changing
- Deep changes of objects cannot be observed in mobx
- How do I get the Date to work correctly on my app?
- How to print a string that is inside an object in js?
- Multiple Dropdown in reactjs
- react-dropzone opens files chooser twice
- React: cant get output inside a functional component
- React Components to SvelteKit - Objects with HTML in attribute (JSX rendering) to Script tag
- React/Redux can't iterate over array in state