Rendering every iteration of an array sort in React - reactjs

I'm trying to build a simple app in react that takes an unsorted array (this.state.dataset) then insertion sorts it and renders each iteration of the sorting process.
Because React is asynchronous placing a setstate after each array change does not work. Any ideas how to get around this?
I was able to do this with bubble sort by simply exiting the function after each array change then rendering it, then restarting the bubble sort with the updated array. However I can't get that approach to work here. Very inefficient I know, sorry I am new to this..
render() {
return (
<div className="buttons">
<button onClick={this.sort}>Insertion Sort</button>
</div>
);
}
sort(e) {
this.myInterval = setInterval(() => {
let arr = this.insertionSort();
this.setState({
dataset: arr,
});
}
}, 1000);
insertionSort(e) {
let inputArr = this.state.dataset
let length = inputArr.length;
for (let i = 1; i < length; i++) {
let key = inputArr[i];
let j = i - 1;
while (j >= 0 && inputArr[j] > key) {
inputArr[j + 1] = inputArr[j];
j = j - 1;
return inputArr //Added by me to stop loop and render (probably wrong solution)
}
inputArr[j + 1] = key;
return inputArr //Added by me to stop loop and render (probably wrong solution)
}
return inputArr;
};
(I have the this.state.dataset rendering in my render() method but excluded for brevity's sake

One possible solution may be to store the values required for iterating the array in the state. On each modification, you can update the state and return from the sorting function.
Because React is asynchronous placing a setState after each array change does not work. Any ideas how to get around this?
The setState function takes a second callback parameter that is called when the state updates. This means you can effectively treat state updates as synchronous.
Here is working implementation using this method:
(This is written in React Native but the logic is the same for regular React)
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
i: 1,
j: 0,
data: [...initialData],
};
}
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={({ item }) => <Text>{item}</Text>}
/>
<Button title="Sort" onPress={this.sort} />
<Button title="Reset" onPress={this.reset} />
</View>
);
}
sort = () => {
const { i, j, key, data: oldData } = this.state;
const nextSort = () => setTimeout(this.sort, 500);
if (i == oldData.length) {
return;
}
const data = [...oldData];
const value = key ? key : data[i];
if (j >= 0 && data[j] > value) {
data[j + 1] = data[j];
this.setState({ j: j - 1, data, key: value }, nextSort);
return;
}
data[j + 1] = value;
this.setState({ i: i + 1, j: i, data, key: undefined }, nextSort);
};
reset = () => this.setState({ data: [...initialData], i: 1, j: 0, key: undefined });
}
One final thing worth mentioning in your existing implementation is the mutation of state. When you have an array in your state, you cannot modify the array as this will cause issues when you call setState.
For example, your variable dataSet is stored in the state. You then set inputArr to a reference of the state value dataSet with:
let inputArr = this.state.dataset
When you now call inputArr[j + 1] = inputArr[j]; the original array (in your state) is updated. If you call setState with inputArr React will compare it against dataSet. As you have modified dataSet the values will match inputArr which means the state won't update.
You can see a workaround for this issue in my solution where I copy the dataSet into a new array with:
const data = [...oldData]
This will prevent the array in your state from updating.

Related

UseEffect doesn't execute itself before rest of the code. Normal or not?

currently I am working on a project and find myself in a bothersome situation. Is it normal for the components to load before useEffect?
On my page I want to implement pagination on sidebar. I have state which will determine current page and that state which is number will be an index which will take nested array and show the content.
However data is an array without nested arrays and firstly I should convert that array into array with nested ones. Because that, I want to run that inside side effect because it should only be done at initial loading.
Now I am trying with hardcoded values and later will set dynamic ones.
The problem now is that useEffect doesn't run first and the rest of code actually executes itself before useEffect and I got errors like "MenuList.js:173 Uncaught TypeError: DUMMY_FOOD[0].map is not a function" and ect. I know that my array is not in right format hence if I log without this [0] it works.
What is problem?
Code:
const MenuList = () => {
const navigate = useNavigate();
const location = useLocation();
const params = useParams();
const [page, setPate] = useState(0);
useEffect(() => {
const pages = Math.ceil(DUMMY_FOOD.length / 5);
const arr = [];
let helpArr = [];
let c = 0;
for (let i = 0; i < pages; i++) {
for (let j = c; j < c + 5; j++) {
console.log("picapicapiac");
helpArr.push(DUMMY_FOOD[j]);
}
c += 5;
arr.push(helpArr);
helpArr = [];
}
console.log(arr);
DUMMY_FOOD = arr;
}, []);
console.log(DUMMY_FOOD);
const queryPrams = new URLSearchParams(location.search);
const sort = queryPrams.get("sort");
const onNextPageHandler = () => {};
const onPreviousPageHandler = () => {};
const onSortPageHandler = () => {
navigate(`/menu/${params.foodId}/?sort=${sort === "asc" ? "desc" : "asc"}`);
sort === "asc"
? (DUMMY_FOOD = DUMMY_FOOD.sort((a, b) => a.foodPrice - b.foodPrice))
: (DUMMY_FOOD = DUMMY_FOOD.sort((a, b) => b.foodPrice - a.foodPrice));
};
return (
<Fragment>
<div className={classes["menu-list"]}>
{DUMMY_FOOD.map((foodObj) => (
<MenuItem key={foodObj.id} foodObj={foodObj} />
))}
</div>
<div className={classes["menu-list__buttons"]}>
<Button type="button" onClick={onPreviousPageHandler}>
Page 2
</Button>
<Button type="button" onClick={onSortPageHandler}>
{sort === "asc" ? `Descending &#8593` : `Ascending &#8595`}
</Button>
<Button type="button" onClick={onNextPageHandler}>
Page 3
</Button>
</div>
</Fragment>
);
};
export default MenuList;
This is how useEffect works. It is simply explained in the react docs:
What does useEffect do? By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API.
This is expected behavior, useEffect is not a synchronous function.
What you want to do is make sure your arrays have items in them and are not null/undefined, to make sure renders don't break.
From React's docs:
Unlike componentDidMount or componentDidUpdate, effects scheduled with useEffect don’t block the browser from updating the screen. This makes your app feel more responsive. The majority of effects don’t need to happen synchronously.
Using your Dummy_food variable below.. not sure where it's coming from but I kept it in the code.
useEffect(() => {
const pages = Math.ceil(DUMMY_FOOD.length / 5);
const arr = [];
let helpArr = [];
let c = 0;
for (let i = 0; i < pages; i++) {
for (let j = c; j < c + 5; j++) {
console.log("picapicapiac");
helpArr.push(DUMMY_FOOD[j]);
}
c += 5;
arr.push(helpArr);
helpArr = [];
}
console.log(arr);
DUMMY_FOOD = arr;
}, []);
Have a portion that displays your links. This will not error out if there are no links at render.
const RenderPagination= () => {
return DUMMY_FOOD.map((f, index) => {
return (
<li>{f}</li>
);
});
};
Then where your displaying your items...
{RenderPagination()}

React state taking previous initialized values when updating

I am having an issue with react.
I have an array of states of a task whether it is pending or completed or running.
I have an used an array in use state like this
const [messageState, setMessageState] = useState<string[]>(new Array(6).fill('Pending...'));
All that has been initialized to pending first.
And then the messages come from Kafka and according to that, I am updating the state.
useEffect(() => {
if(message.info && message.info.log.indexOf('fromScript') ! == -1) {
const {info} = message
const {err} = info
for(let i=0; i < 6; i++){
const array = setTableContent(i, err)
console.log(array);
setMessageState(array)
}
}
}
)
The function for setTableContent is
const setTableContent = (row: number, err: any) => {
const value = getStatus(row, err);
const newArray = [...messageState]
newArray[row] = value;
return newArray;
}
where getStatus is a function which fetches the status for all the tasks on every kafka message.
Now the problem is that every time even if I am updating the state of messageType in useEffect snippet, I am still getting the same initialized values on the 3rd line of setTableContent function. Why is this happening I am not able to understand.
Please help. Thank you in advance.
I am still not sure why I can't update an array state in a loop but I have found a turn around for this.
Rather than putting
setMessageState() in useState, i have put the for loop in the function setTableContent() itself.
const setTableContent = (row: number, err: any) => {
const values = []
for(let i=0; i < 6; i++) {
values.push(getStatus(i, err));
}
setMessageType(values);
}
And now its working

best way to update state array with delay in a loop

I am learning react by working on a sorting algorithm visualizer and I want to update the state array that is rendered, regularly in a loop.
Currently I am passed an array with pairs of values, first indicating the current index and value, and second with its sorted index and value.
[(firstIdx, value), (sortedIdx, value), (secondIdx, value), (sortedIdx, value) ... etc]
some actual values:
`[[1, 133], [0, 133], [2, 441], [2, 441], [3, 13], [0, 13] ... ]`
What I want to do is cut the value out of the array, splice it into the correct position, while updating the state array rendered in each step. effectively creating an animation with the state array.
Right now when I run below function, my state array instantly becomes the sorted array because of the batching. I would like there to be a delay between each state update in the loop.
code snippet that I've tried.
insertionSort(changeArray) {
const arrayBars = document.getElementsByClassName('array-bar')
// I want to keep track which index to move from/to so I instantiate it outside the loop.
let [barOneIdx, barOneValue] = [0, 0];
let [barTwoIdx, barTwoValue] = [0, 0];
// Copy of the state array that I will modify before setting the state array to this.
let auxArray = this.state.array.slice();
for (let i = 0; i < changeArray.length; i++) {
// This tells me whether it is the first or second pair of values.
let isFirstPair = 1 % 2 !== 1;
if (isFirstPair) {
// first set of values is the current index + height
[barOneIdx, barOneValue] = changeArray[i];
// Changes the current bar to green.
setTimeout(() => {
arrayBars[barOneIdx].style.backgroundColor = 'green';
}, i * 300);
} else {
// second set of values is the sorted index + height.
[barTwoIdx, barTowValue] = changeArray[i];
// Cut the current bar out of the array.
let cutIdx = auxArray[barOneIdx];
auxArray.splice(barOneIdx, 1);
// Splice it into the sorted index
auxArray.splice(barTwoIdx, 0, cutIdx);
// Changes the color of the bar at the correct sorted
// index once, and then again to revert the color.
setTimeout(() => {
// Set the state array with the new array. NOT WORKING
// Instantly sets state array to final sorted array.
// I want this to run here with a delay between each loop iteration.
this.setState({ array: auxArray });
arrayBars[barTwoIdx].style.backgroundColor = SECONDARY_COLOR;
}, i * 300);
setTimeout(() => {
arrayBars[barTwoIdx].style.backgroundColor = PRIMARY_COLOR;
}, i * 300);
}
}
}
https://codesandbox.io/s/eager-yonath-xpgjl?file=/src/SortingVisualizer/SortingVisualizer.jsx
link to my project so far with all the relevant functions and files.
On other threads say not to use setState in a loop as they will be batched and run at the end of the block code. Their solutions won't work for my project though as I want to create an animation with the state array.
What would be the best way to implement this?
If you are familiar with ES6 async/await you can use this function
async function sleep(millis) {
return new Promise((resolve) => setTimeout(resolve, millis));
}
async function insertionSort() {
// you code logic
await sleep(5000) //delay for 5s
this.setState({array : auxArray});
}
I have put together a basic version of what you're trying to achieve. I depart from your approach in a few important ways, one of which is the use of an async function to delay state updates. I also change the way the original array is generated. I now create an array that includes the height of the bars as well as its color. This is necessary to accomplish the color changes while moving the bars to their right spots.
There is also no need for your getInsertionSortAnimations function any more as the sorting is done inside the class using the reduce function. I will just paste the entire code here for future reference, but here is the Sandbox link: https://codesandbox.io/s/damp-bush-gkq2q?file=/src/SortingVisualizer/SortingVisualizer.jsx
import React from "react";
import "./SortingVisualizer.css";
//import { getMergeSortAnimations } from "../SortingAlgorithms/MergeSort";
import { setTimeout } from "timers";
// Original color of the array bars.
const PRIMARY_COLOR = "aqua";
// Color we change to when we are comparing array bars.
const SECONDARY_COLOR = "green";
// Speed of the animation in ms.
const ANIMATION_SPEED_MS = 400;
// Number of array bars.
const NUMBER_OF_BARS = 10;
const sleep = (millis) => {
return new Promise((resolve) => setTimeout(resolve, millis));
};
function arraymove(arr, fromIndex, toIndex) {
var element = arr[fromIndex];
arr.splice(fromIndex, 1);
arr.splice(toIndex, 0, element);
}
export default class SortingVisualizer extends React.Component {
constructor(props) {
super(props);
this.state = {
array: []
};
}
// React function runs first time component is rendered, client side only.
componentDidMount() {
this.resetArray();
}
resetArray() {
const array = [];
for (let i = 0; i < NUMBER_OF_BARS; i++) {
array.push({
height: randomIntfromInterval(10, 200),
color: PRIMARY_COLOR
});
}
this.setState({ array });
}
animateSorting = async (sorted_array) => {
const { array } = this.state;
for (let i = 0; i < sorted_array.length; i++) {
const orig_index = array.findIndex(
(item) => item.height === sorted_array[i]
);
array[orig_index].color = SECONDARY_COLOR;
this.setState(array);
await sleep(ANIMATION_SPEED_MS);
arraymove(array, orig_index, i);
this.setState(array);
if (orig_index !== i) await sleep(ANIMATION_SPEED_MS);
}
};
insertionSort() {
const { array } = this.state;
const sorted = array.reduce((sorted, el) => {
let index = 0;
while (index < sorted.length && el.height < sorted[index]) index++;
sorted.splice(index, 0, el.height);
return sorted;
}, []);
this.animateSorting(sorted);
}
render() {
const { array } = this.state;
return (
// Arrow function to use "this" context in the resetArray callback function: this.setState({array}).
// React.Fragment allows us to return multiple elements under the same DOM.
<React.Fragment>
<div className="button-bar">
<button onClick={() => this.resetArray()}>Generate Array</button>
<button onClick={() => this.insertionSort()}>Insertion Sort</button>
<button onClick={() => this.mergeSort()}>Merge Sort</button>
<button onClick={() => this.quickSort()}>Quick Sort</button>
<button onClick={() => this.heapSort()}>Heap Sort</button>
<button onClick={() => this.bubbleSort()}>Bubble Sort</button>
</div>
<div className="array-container">
{array.map((item, idx) => (
<div
className="array-bar"
key={idx}
// $ dollarsign makes a css variable???
style={{
backgroundColor: `${item.color}`,
height: `${item.height}px`
}}
></div>
))}
</div>
</React.Fragment>
);
}
}
// Generates random Integer in given interval.
// From https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript
function randomIntfromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
Gotcha: There is a bug in the code however, which should be a piece of cake for you to fix. Notice how it behaves when two or more bars happen to have the same exact height.

useEffect enters infinite loop when using React in Hooks

I'm paging with react. When doing this, I transfer the state in a parent component here. I transfer the information I transfer to a different state with a new array, but when I do it with useEffect, it enters an infinite loop. I couldn't set a dene state.
const Pagination = ({ posts }) => {
const gecici = posts
const sabit = 5;
const [dene, setDene] = useState([])
const [degisken, setDegisken] = useState(0)
useEffect(() => {
degistir()
console.log(dene)
}, [dene])
const degistir =() => {
var i = 1,
j;
if (sabit <= gecici.length) {
for (j = 0; j < (gecici.length / sabit); j++) {
setDene([
{
id: i, include:
gecici.slice(degisken, degisken + sabit)
}
]);
i += 1;
setDegisken(degisken+sabit)
}
}
}
Since I'm paging, I'm adding content up to a 'sabit' value on each page. The value i indicates the page number here.
The value of j is to fill the array up to the total number of pages.
The way the useEffect dependency array works is by checking for strict (===) equivalency between all of the items in the array from the previous render and the new render. Therefore, putting an array into your useEffect dependency array is extremely hairy because array comparison with === checks equivalency by reference not by contents.
const foo = [1, 2, 3];
const bar = foo;
foo === bar; // true
const foo = [1, 2, 3];
const bar = [1, 2, 3];
foo === bar; // false
So, since you have this:
useEffect(() => {
degistir()
console.log(dene)
}, [dene])
Your component enters an infinite loop. degistir() updates the value of dene to a new array. But even if the contents are the same, the reference of dene has changed, and the useEffect callback fires again, ad infinitum.
The solution depends a bit on what exact behavior you want to have happen. If you want the useEffect callback to trigger every time the size of the array changes, then simply use the length of the array in the dependency array, instead of the array itself:
useEffect(() => {
degistir()
console.log(dene)
}, [dene.length])
A less ideal solution is to convert your array into a string and compare the old stringified array to the new stringified array:
useEffect(() => {
degistir()
console.log(dene)
}, [JSON.stringify(dene)])
This is extremely inefficient but might work if the number of items in the array is small.
The best option is probably to get rid of the useEffect entirely. It is unlikely that you actually need it. Instead, you can probably accomplish your pagination as a pure result of: 1) The total number of posts, and 2) the current page. Then just render the correct posts for the current page, and have a mechanism for updating the current page value.
Perhaps something like this? The naming of your variables is confusing to me since I speak English only:
const Pagination = ({ posts }) => {
const gecici = posts
const sabit = 5;
const [degisken, setDegisken] = useState(0)
let dene = [];
var i = 1,
j;
if (sabit <= gecici.length) {
for (j = 0; j < (gecici.length / sabit); j++) {
dene = [
{
id: i, include:
gecici.slice(degisken, degisken + sabit)
}
];
i += 1;
}
}

Which SectionHeader is Sticky in react-native?

I'm using React-Native's SectionList component to implement a list with sticky section headers. I'd like to apply special styling to whichever section header is currently sticky.
I've tried 2 methods to determine which sticky header is currently "sticky," and neither have worked:
I tried to use each section header's onLayout prop to determine each of their y offsets, and use that in combination with the SectionList onScroll event to calculate which section header is currently "sticky".
I tried to use SectionList's onViewableItemsChanged prop to figure out which header is currently sticky.
Approach #1 doesn't work because the event object passed to the onLayout callback only contains the nativeEvent height and width properties.
Approach #2 doesn't work because the onViewableItemsChanged callback appears to be invoked with inconsistent data (initially, the first section header is marked as viewable (which it is), then, once it becomes "sticky," it is marked as not viewable, and then with further scrolling it is inexplicable marked as viewable again while it is still "sticky" [this final update seems completely arbitrary]).
Anyone know a solution that works?
While you creating stickyHeaderIndices array in render() method you should create an object first. Where key is index and value is offset of that particular row, eg. { 0: 0, 5: 100, 10: 200 }
constructor(){
super(props);
this.headersRef = {};
this.stickyHeadersObject = {};
this.stickyHeaderVisible = {};
}
createHeadersObject = (data) => {
const obj = {};
for (let i = 0, l = data.length; i < l; i++) {
const row = data[i];
if (row.isHeaderRow) {
obj[i] = row.offset;
}
}
return obj;
};
createHeadersArray = data => Object.keys(data).map(str => parseInt(str, 10))
render() {
const { data } = this.props;
// Expected that data array already has offset:number and isHeaderRow:boolean values
this.stickyHeadersObject = this.createHeadersObject(data);
const stickyIndicesArray = this.createHeadersArray(this.stickyIndicesObject);
const stickyHeaderIndices = { stickyHeaderIndices: stickyIndicesArray };
return (<FlatList
...
onScroll={event => this.onScroll(event.nativeEvent.contentOffset.y)}
{...stickyHeaderIndices}
...
renderItem={({ item, index }) => {
return (
{ // render header row
item.isHeaderRow &&
<HeaderRow
ref={ref => this.headersRef[index] = ref}
/>
}
{ // render regular row
item.isHeaderRow &&
<RegularRow />
}
);
}}
/>)
Then you have to monitor is current offset bigger than your "titleRow"
onScroll = (offset) => {
Object.keys(this.stickyHeadersObject).map((key) => {
this.stickyHeaderVisible[key] = this.stickyHeadersObject[key] <= offset;
return this.headersRef[key] && this.headersRef[key].methodToUpdateStateInParticularHeaderRow(this.stickyHeaderVisible[key]);
});
};

Resources