score:2
Accepted answer
it has to do with react batching state updates in event handlers
please check this link
i tried to solve it with changing sort to be a generator function and iterator pattern with useeffect hook. -> my solution
its not a polished solution. but maybe it can help you come up with some ideas :)
if you cannot access the link here is the code
app.js
import sort from "./sort";
import "./styles.css";
import { useeffect, usestate, useref } from "react";
const delay = (ms) => new promise((r) => settimeout(r, ms)); // helper func
const initialarray = [72, 22, 402, 131, 30];
const initialdata = { data: initialarray, sortstep: -1 };
export default function app() {
const [state, setstate] = usestate(() => initialdata);
const iterator = useref();
const runsort = async () => {
if (state.sortstep >= 0) {
const { value, done } = iterator.current.next();
if (!done) { // here since sort is not done.we go to next sortstep
await delay(1000);
setstate((s) => ({ ...s, data: value, sortstep: s.sortstep + 1 }));
} else {
// sorting is done. maybe reset things up.
}
}
};
const startsort = () => {
iterator.current = sort(initialarray);
setstate((s) => ({ ...s, data: initialarray, sortstep: 0 }));
// here we initiate sort by setting the sortstep to zero
};
useeffect(() => {
runsort();
}, [state.sortstep]); // whenever ${sortstep} changes we try to sort again it to next step untill the sorting is complete
return (
<div classname="app">
<button onclick={startsort}>insertion sort</button>
{state.sortstep >= 0 && <h4>step: {state.sortstep}</h4>}
{state.data.map((val, i) => (
<div key={`${val}${i}`}>{val}</div>
))}
</div>
);
}
sort.js
function* sort(data) {
const inputarr = [...data];
let n = inputarr.length;
for (let i = 1; i < n; i++) {
// choosing the first element in our unsorted subarray
let current = inputarr[i];
// the last element of our sorted subarray
let j = i - 1;
while (j > -1 && current < inputarr[j]) {
inputarr[j + 1] = inputarr[j];
j--;
}
inputarr[j + 1] = current;
yield inputarr;
}
}
export default sort;
score:0
use anonymous function when you are setting the state based on to previous state
setdata((state, props) => {
//do something here
});
Source: stackoverflow.com
Related Query
- React components not updating with state change
- React Child with useEffect() not updating on Parent State Change
- React Component not updating with state change
- Component not updating on state change with React Router
- React Child Component Not Updating After Parent State Change
- Why is my react component not updating with state updates?
- Why is the DOM not updating with state change in ReactJS?
- Props not updating when redux state change in React Hooks
- react is not updating functional component state on input change
- React not updating state with setState with Array of object
- Map of React Components not re rendering on State Change
- Redux - State is updating but React components are not
- Updating state on route change with React Redux
- React UI not updating on state change
- useContext not updating on state change in React
- react stateless child components do not update on state change in parent component
- REACT + REDUX: on redux state change mapStateToProps updating state but view is not rendering as per new state
- React custom hook with event listener not works while updating the state
- React component does not update with the change in redux state
- react state not updating on input change
- React / Redux Components not re-rendering on state change
- React Hooks state is not updating with correct output
- React JS component not updating on state change
- Having problem with State not updating in React
- React useCallback not updating state onChange on the first change
- React not updating state with setState correctly inside promises
- Component local state not updating with react custom hooks
- React State Not Updating with Conditional Statement
- Why is my React component not re-rendering upon state change with Date?
- Component with setinterval not updating on context state change
More Query from same tag
- How can I map array with multiple objects and display on chart?
- React - Updating State From a Child Component, Then Doing Something Based on State
- onMouseDown/onClick event on <div> inside <div>
- Access current record in admin on rest edit
- Error: sending a transaction requires a signer while calling aggregate function of Multicall Contract Ethereum
- React state keep old state
- Changing style property with setState in React
- React counter getting out of sync when tab is not focused
- How to pass props down to child component in React
- Unable to access data which is copied using useState hook
- Display images from S3
- Using .map() with useEffect and Api
- Nesting routes in React using HashRouter
- 'match' property not set on props when using MemoryRouter in test
- How to reset the state in react when component is rendered or shown?
- How do I offset Material-UI Popper (popper.js library) position on y-axis?
- Error message caught by Axios is undefined in production, but works locally?
- Pass value from map to state
- React import html - Module parse failed: You may need an appropriate loader to handle this file type
- Why is SVG textPath not working in Firefox when rendered by React
- Why am Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: number
- In React how would I disable onSubmit call for some text fields and not others?
- Unexpected Token Error Defining Data in JSX React
- How to populate <SelectInput> choices with already fetched data
- How to make decimal to take up to two(2) values of series in amCharts?
- Determine stateless component name from within that component in react
- React-router not matching any route on Link or NavLink click (but it works if we do a refresh)
- 'Can't perform a React state update on an unmounted component' ERROR when accessing the context api
- Why I cannot change the value of my variable?
- How to avoid input value reset in Reactjs?