score:1
issue
the issue here is you've a stale enclosure of the currimageindex
state value from the initial render when the increment
callback was setup in the interval timer. you're correctly using a functional state to increment the currimageindex
value, but the currimageindex
value in the increment
function body is and always will be that of the initial state value, 0
.
solution
a common solution here would be to use a react ref to cache the currimageindex
state so the current value can be accessed in callbacks.
example:
const [currimageindex, setcurrimageindex] = usestate(0);
const currentimageindexref = useref();
useeffect(() => {
// cache the current state value
currentimageindexref.current = currentimageindex;
}, [currimageindex]);
const increment = () => {
// access the current state value
if (currentimageindexref.current + 1 < url.length) {
setcurrimageindex((oldcount) => oldcount + 1)
}
else {
setcurrimageindex(0)
}
}
useeffect(() => {
const id = setinterval(increment, 1000);
return () => clearinterval(id);
}, []);
a simpler solution is to just access the url
value that is closed over in component scope with the state updater callback. use a ternary operator to check if adding 1 to the current value is still less than the url
length and state + 1, otherwise reset by returning 0
. note however that if the url
array is dynamic and the length changes this solution breaks for the same reason, the url
value from the initial render is closed over in scope.
const increment = () => {
setcurrimageindex((count) => count + 1 < url.length ? count + 1 : 0);
}
and imo the simplest solution is to just increment the currimageindex
state always and take the modulus of the url
length to always compute a valid, in-range index value. if the url
array changes, it doesn't matter as the modulus function will always compute a valid index.
const { url } = props;
const [index, setindex] = usestate(0);
const increment = () => setindex(i => i + 1);
useeffect(() => {
const id = setinterval(increment, 1000);
return () => clearinterval(id);
}, []);
const currimageindex = index % url.length;
return (
<div classname={styles.container}>
<div classname={styles.header}>preview of gif:</div>
<img src={url[currimageindex]} alt="gif preview" classname={styles.image} />
<div>{currimageindex}</div>
</div>
);
score:1
the reason is that the callback passed on setinterval only access the currimageindex
variable in the first render, not the new value while render so you will always get currimageindex = 0
and pass the condition if (currimageindex + 1 < url.length)
. i update your code and make it work like your expectation: https://stackblitz.com/edit/react-y6fqwt
Source: stackoverflow.com
Related Query
- How to increment a state variable every second in React
- How to increment a React state every second using setInterval?
- How do I lower a variable by a certain value every second in react
- How to pass a state className variable to another component in react
- React Native: How to stop map markers from re-rendering on every state update
- react how to call state variable from another class?
- How does React State Hook gets the state variable name from the ES6 Destructuring Assignment
- how to put a file in state variable with react hooks
- How to increment a variable inside .map() in react js
- How to filter array & update state when every click in React
- How to set a state variable in the parent of a React Route?
- How to update redux state using a react variable passed up to the component from a child
- How to set a state Array from a global variable in React
- React Hooks: how to update state variable based on another state variable update
- How to get ThemeContext state as variable in Javascript inside react component?
- How do I stop state store data from accumulating in a redux component every time I navigate to it using react router
- How do I add a JS state variable of 1 React component for use in other components?
- How to not mutate a prop variable used as state in a React component without a dummy variable?
- If I make a variable inside a react component, how do I re-access it on a state change?
- React how to update ui after every loop iteration which changes state array?
- React - How to use the current state value as a variable so i can set as a index inside an array
- How to update a clock every second in React js recursively?
- How do I update state when a window variable changes in react
- how to go through react state variable array and determine if it has one true value
- React JS - How to set state of variable inside variable?
- How to set state for individual state variable in react + typescript?
- How to add React JSX for every item in state array?
- React Testing Library - how to set initial value of state variable
- using setInterval to increment variable every second - not updating
- How do I increment the count of a selected index of state object using setState method given by useState hook in my react application
More Query from same tag
- How to change window.location.href according to return value?
- Is it possible to map only a portion of an array? (Array.map())
- Multiple custom markers import in Leaflet
- Cannot read property 'substr' of undefined in React JS inside map function
- Assign the same values to multiple class properties the pretty way
- how to test component parameters in constructor with Jest and Enzyme
- how do i redirect a user to a "Not Found Page" when user tries to append random string to the URL?
- Run Effect hook only when both dependencies change
- Integrating socket.io(^3.0.0) with Strapi Server("3.2.5") CORS Error
- Converting object values into an array in Javascript?
- React Hooks useEffect, adding dependency triggers infinite loop
- how to listen for route change in react-router-dom v6
- curly braces in es6 arrow function for each
- How do I include an `<img>` in ReactJS?
- ReactJS: Can I separate a function that changes state in a separate component?
- Accessing JSON from public folder in ReactApp
- react-router-dom match object isExact false
- Override some material-ui class styles but preserve the default ones
- Why my redux state always return with default case?
- test restapi inside useeffect in jest
- Why can't I delete global NPM package on Ubuntu?
- How to get the date ranges of a given week number in JS
- React app docker container exits/restarts after executing npm run build command
- How to dynamically modify the values inside an array according to a length of a string?
- How do I remove a View in React Native
- Styled Components Global style duplicated in Next
- Element type is invalid : While importing tsx files
- In useEffect, what's the difference between providing no dependency array and an empty one?
- Prevent Double Submit in Stateless react-form
- custom-environment-variables.js cannot be read error in react application