Too many re-renders in React - javascript

The program should take the input user typed, search the data and return results in a drop down list.
When the userinput is more than 3 symbols, the Search() is called and I get "Error: Too many re-renders". Can't find where is the render loop.
import LTCityNames from "../lt-city-names.json"; //JSON object
const Openweathermap = () => {
const [searchList, setSearcList] = useState([]); //drop down list according to search word
const [text, setText] = useState(""); //text in the input field
const Search = (userinput) => {
let correctResult = "";
let dropdownList = [];
const regex = new RegExp(`^${userinput}`, "i");
for (let i = 0; i < LTCityNames.length; i++) {
correctResult = regex.test(LTCityNames[i].name);
if (correctResult){
dropdownList.push(LTCityNames[i]);
setSearcList(dropdownList);
}
}
};
const onChangeInput = (userinput) => {
setText(userinput);
if (userinput.length > 2) {
Search(userinput);
}
};
return (
<input
value={text}
onChange={(e) => {onChangeInput(e.target.value)} }
type="text"
placeholder="Enter address"
></input>
<div id="myDropdownWeather" className="dropdown-content">
{searchList.map((itemInArray) => {
return (
<ul>
<li>{itemInArray.name}</li>
</ul>
);
})
}

I think you must use useEffect like this:
const [text, setText] = useState(""); //text in the input field
const lastFilter = useRef(text);
useEffect(() => {
if (lastFilter.current !== text && text.lenght>2) {
Search(userinput);
lastFilter.current = text;
}
}, [text]);
const onChangeInput = (event) => {
var userinput=event.target.value;
setText(userinput);
};
and change
onChange={(e) => {onChangeInput(e.target.value)} }
to
onChange={(e) => {onChangeInput(e)} }

First: Why you are getting "Error: Too many re-renders"?
When you are using React Functional Components, every time you call a "setState" React reload all your Component, and since you are using functions inside you component these functions are also being loaded every single time your component change. So, when you type your search, the element will re-render uncontrollably.
Solving the problem:
Every time you want to use a function inside a React Functional Component you must use React.useCallback because this way you can control exactly when a function should be reloaded in memory preventing the errors you are getting.
One more thing, inside your return when you are working with react you cannot return more than one JSX Element, this will also cause you a lot of problems, to solve this you can use the fragment element <> ... </> or any other master element that will hold all the others (fragment elements will not interfere with you CSS).
The Code:
import React, { useCallback, useState } from 'react';
import LTCityNames from '../lt-city-names.json'; // JSON object
const Openweathermap = () => {
const [searchList, setSearcList] = useState([]); // drop down list according to search word
const [text, setText] = useState(''); // text in the input field
const Search = useCallback((userinput) => {
const correctResult = '';
const dropdownList = [];
const regex = new RegExp(`^${userinput}`, 'i');
for (let i = 0; i < LTCityNames.length; i++) {
const correctResult = regex.test(LTCityNames[i].name);
if (correctResult) {
dropdownList.push(LTCityNames[i]);
setSearcList(dropdownList);
}
}
}, []);
const onChangeInput = useCallback(
(e) => {
const userinput = e.target.value;
setText(userinput);
if (userinput.length > 2) {
Search(userinput);
}
},
[Search],
);
return (
<> // Fragment element start
<input
value={text}
onChange={(e) => onChangeInput(e)}
type="text"
placeholder="Enter address"
/>
<div id="myDropdownWeather" className="dropdown-content">
{searchList.map((itemInArray) => {
return (
<ul>
<li>{itemInArray.name}</li>
</ul>
);
})}
</div>
</> // Fragment element end
);
};
Understanding useCallback:
useCallback is a React function that will receive 2 parameters the first one is your function and the second one is an array of parameters that when changed will trigger a reload in memory for the function (every time you use an element that came from outside the function itself you need to use it as a parameter to reload the function in memory).
const myReactFunction = useCallback(() => {}, [a,b,c....] )
Improving you Component Return:
You are not required to use any of the tips listed bellow but they will improve the readability of your code.
Since you are calling your input onChange with (e) => onChangeInput(e) you can change your input to only onChangeInput:
<input
value={text}
onChange={onChangeInput} // same as (e) => function(e)
type="text"
placeholder="Enter address"
/>
The second tip is inside you map function, since you are using arrow functions you are not required to type return():
{searchList.map((itemInArray) => (
<ul>
<li>{itemInArray.name}</li>
</ul>
))}

import LTCityNames from "../lt-city-names.json"; //JSON object
const Openweathermap = () => {
const [searchList, setSearcList] = useState([]); //drop down list according to search word
const [text, setText] = useState(""); //text in the input field
const Search = (userinput) => {
let correctResult = "";
let dropdownList = [];
const regex = new RegExp(`^${userinput}`, "i");
for (let i = 0; i < LTCityNames.length; i++) {
correctResult = regex.test(LTCityNames[i].name);
if (correctResult){
dropdownList.push(LTCityNames[i]);
setSearcList(dropdownList);
}
}
};
const onChangeInput = (userinput) => {
setText(userinput);
if (userinput.length > 2) {
Search(userinput);
}
};
//remove value={text}
return (
<input
onChange={(e) => {onChangeInput(e.target.value)} }
type="text"
placeholder="Enter address"
></input>
<div id="myDropdownWeather" className="dropdown-content">
{searchList.map((itemInArray) => {
return (
<ul>
<li>{itemInArray.name}</li>
</ul>
);
})
}
Remove value = {text}

Related

Call React state methods from external function

I am building a React functional component that uses some state variables, and I am trying to modify some of these variables from an external function thats called on a button click event, but when I pass the reference to the state methods to this external function, all of them are undefined. What could be the cause? If I just put the exact same code within the functional component, it works perfectly as intended.
import React from "react";
import {CodeArea, Table, EmptyField, Button} from '../util/util.js'
import {Step, Load} from "./buttons.js" // The external function in question, Loadfunction
Core(props){
const registersInitial = new Array(32).fill(0);
let buttonNamesInitial = ['LOAD','play', 'step-forward', 'run-to', 'step-back','pause','halt', 'rerun', 'add'];
const [bigText, setText] = React.useState();
const [registers, setRegisters] = React.useState(registersInitial);
const [running, setRunning] = React.useState(false);
const [programCounter, setProgramCounter] = React.useState(0);
const [buttonNames, setButtonNames] = React.useState(buttonNamesInitial);
const [lines, setLines] = React.useState([]);
const getBigText = () => {
return bigText;
}
const getRunning = () =>{
return running;
}
const getButtonNames = () => {
return buttonNames;
}
//... some code here thats irrelevant
function getQuickbarContents(){
let functions = [ //Backend will come here
() => Load(setRunning, getRunning, setButtonNames, getButtonNames, setProgramCounter, setLines, getBigText), //Where Load gets called
() => console.log("code running..."),
() => console.log("stepping to next line..."),
() => console.log("running to location..."),
() => console.log("stepping..."),
() => console.log("pausing..."),
() => console.log("halting..."),
() => console.log("running again..."),
() => console.log("select widget to add...")
]
let contents = [];
let row = [];
for (let i = 0; i<9; i++){
row.push(<Button onClick ={functions[i]} className='quickbar' name={buttonNames[i]}/>);
contents.push(row);
row = [];
}
return contents
}
const divs = [];
let buttons = getQuickbarContents();
divs.push(<div key='left' className='left'><Table name='quickbar' rows='7' cols='1' fill={buttons}/> </div>);
//... some more code to push more components do divs
return divs;}
export default Core;`
Button looks like this:
function Button({onClick, className, name}){
return <button onClick={onClick} className={className} name={name}>{name}</button>
}
and Load like this:
export function Load({setRunning, getRunning, setButtonNames, getButtonNames, setProgramCounter, setLines, getBigText}){
let newButtonName;
if (!getRunning()){ // Functions errors out with getRunning() undefined
herenewButtonName = "Reload";
}
else{ //while running if user wants to reload
newButtonName = "LOAD";
}
let lines = getBigText().split(/\n/);
setLines(lines);
setProgramCounter(0);
setRunning(!getRunning());
const newButtonNames = getButtonNames().map((value, index) =>{
if (index === 0){
return (newButtonName);
}
return value;
})
setButtonNames(newButtonNames);
}
So essentially in my head the flow should be: state methods initialised -> button components created -> wait for click of a button -> update state variablesBut clearly, something goes wrong along the way.
I've tried using inspection mode debugging, which revealed that in fact all of the parameters to Load are undefined when they are evaluated.
Note, that everything works as intended if I change the code up like this, eg. just put the whole function within the React component;
//... everything same as before
function getQuickbarContents(){
let functions = [
() =>{
let newButtonName;
if (!getRunning()){ //User clicks to start running
newButtonName = "Reload";
}
else{
newButtonName = "LOAD";
}
let lines = getBigText().split(/\n/);
setLines(lines);
setProgramCounter(0);
setRunning(!getRunning());
const newButtonNames = getButtonNames().map((value, index) =>{
if (index === 0){
return (newButtonName);
}
return value;
})
setButtonNames(newButtonNames)},
() => console.log("code running..."),
() => console.log("stepping to next line..."),
() => console.log("running to location..."),
() => Step(setRegisters, registers, setProgramCounter, programCounter, lines[programCounter]),
() => console.log("pausing..."),
() => console.log("halting..."),
() => console.log("running again..."),
() => console.log("select widget to add...")
]
//...everything same as before
so consequently the error is somewhere in the way I pass parameters to Load, or maybe I'm doing something I shouldn't be doing in React. Either way I have no clue, any ideas?
Problem was in the way parameters were defined in Load, as #robin_zigmond pointed out. Fixed now.

TypeError: Object(...) is not a function when creating a JS object

I am getting a TypeError: Object(...) is not a function compiler issue and I am not sure why, below are the corresponding files - I am specifically getting an issue where
const mySubmission = GetStudentSubmissionWithUrl();
is run. My function GetStudentSubmissionWithUrl() returns a JavaScript object and I want to assign this object to another JavaScript object.
function Details () {
const mySubmission = GetStudentSubmissionWithUrl();
/* TODO: do the filtering of a submission in the backend instead of right here - will cause a big performance hit */
return (
<React.Fragment>
{mySubmission?.images && <ImageCarousel imageList={mySubmission.images}/>}
<div className="card-body">
<h1 className="title-event">{}</h1>
{mySubmission?.subjectName && <h2 className="title-location"> {mySubmission.subjectName}</h2>}
<br></br>
<div className="row=title">
{mySubmission?.location && <h3 className="submitter-location"> {mySubmission.location}</h3>}
{mySubmission?.description && <p> {mySubmission.description}</p>}
</div>
<br></br>
</div>
{mySubmission?.sources && <Source sourceList={mySubmission.sources}/>}
</React.Fragment>
);
}
export default Details;
Here is where my corresponding GetStudentSubmissionWithUrl() is defined:
import React, { useState, useEffect } from 'react';
import { getAllVerified } from '../util';
//return a StudnetSubmission given the current ulr link that we are in
function GetStudentSubmissionWithUrl() {
const [submissions, setSubmissions] = useState(null);
useEffect(() => {
const fetchData = async () => {
const data = await getAllVerified(); //just get the one
setSubmissions(data);
};
fetchData();
}, []);
let str = JSON.stringify(window.location.pathname);
let submissionId = str.split("/").pop();
submissionId = submissionId.replace('"', '');
let mySubmission;
if (submissions != null) {
var arrayLength = submissions.length;
for (var i = 0; i < arrayLength; i++) {
let string_id = submissions[i].id;
string_id = string_id.replace('"', '');
if (submissionId === string_id) {
mySubmission = JSON.parse(JSON.stringify(submissions[i]));
}
}
}
return mySubmission;
}
export default GetStudentSubmissionWithUrl;
Any help would be much appreciated - thanks in advance!

Convert jQuery Animation to React Hook

I am building an animation where the letters of two words appear one by one, similar to a slide-in effect. I have the code made with jQuery, but I need to implement it in my React app (built with hooks). The code that I have takes the text, splits it creating individual letters, and adds spans between those letters. This is the following code that I need to convert to React:
const logoText = document.querySelector('.logo');
const stringText = logoText.textContent;
const splitText = stringText.split("");
for (let i=0; i < splitText.length; i++) {
text.innerHTML += "<span>" + splitText + "</span>"
}
let char = 0;
let timer = setInterval(onTick, 50)
I was wondering if you guys could help me figure it out. Thanks a lot!
You need to iterate over the text and create a timeout function for every letter with a different time of execution, that way will be visible the slide effect you are expecting:
Custom hook
const useSlideInText = text => {
const [slide, setSlide] = useState([]);
useEffect(() => {
Array.from(text).forEach((char, index) => {
const timeout = setTimeout(
() =>
setSlide(prev => (
<>
{prev}
<span>{char}</span>
</>
)),
index * 100
);
});
}, []);
return slide;
};
Usage
function App() {
const slide = useSlideInText("hello");
return (
<div>
{slide}
</div>
);
}
Working example
I am assuming the React components that you want to run this hook in possess the text you want to split. I am also assuming that on the interval, you want to reveal more of the text. In that case my example solution would look like this:
Hook
import {useState, useEffect} from "react";
const useSlideInText = (text) => {
const [revealed, setRevealed] = useState(0);
useEffect(() => {
if (revealed < text.length) {
setTimeout(() => setRevealed(revealed + 1), 50);
}
});
return text.split('').slice(0, revealed).map((char) => (<span>{char}</span>));
}
Example usage
const MyComponent = (props) => {
const displayText = useSlideInText(props.text);
return <div>{displayText}</div>;
};
going off of the other answer:
const generateDisplayTest = (text, numChars) => text.split('').slice(0, numChars).map((char) => (<span>{char}</span>));
const MyComponent = (props) => {
const [revealed, setRevealed] = useState(0);
useEffect(() => {
if (revealed < props.text.length) {
setTimeout(() => setRevealed(revealed + 1), 50);
}
}, [revealed]);
const displayText = generateDisplayTest(props.text, revealed);
return <div>{displayText}</div>;
};
including [revealed] in the useEffect means that useEffect will run every time that revealed changes. Also I always feel that useState/useEffect should live on the component, it has been that way in the place I worked but I'm not sure if that is industry standard.

How to do click item with pagination?

Use react.js. Catching hard to understanding error. My component without pagination work well - show you all items and you can see the item by click. Pagination work fine too, but i cant click on item in item list. Actualy i can click, but displaying only first page items. If you click on item from 2-nd(3,4...n) page you get item from 1-st page.
Open CodePen with my code
export function ListOfItems() {
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
const users = useSelector(state => state);
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = users.slice(indexOfFirstPost, indexOfLastPost);
const paginate = pageNumber => setCurrentPage(pageNumber);
let items = currentPosts.map(function (value, index) {
return (
<form key={index}>
<div className="input-group">
<div className="input-group-prepend">
<Link className="input-group-text" to={`${url}/${index}`}>
{value.name}
</Link>
</div>
</div>
</form>
)
});
return (
<div>
<div>{items}</div>
<Pagination postsPerPage={postsPerPage} totalUsers={users.length} paginate={paginate}/>
</div>
)
}
Recently I've built something like you.
There is a more clean way to do it.
I recommend you to separate your logic in custom hooks.
For example, you can create custom hook:
export const usePagination = (posts, defaultPage = 1, amountPerPage = 10) => {
const [currentPage, setCurrentPage] = useState(defaultPage);
const [postsPerPage] = useState(amountPerPage);
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
let currentPosts = [];
let amountOfPages = 0;
if (Array.isArray(posts)) {
currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
amountOfPages = Math.ceil(posts.length / postsPerPage);
}
return {
setCurrentPage,
amountOfPages,
currentPosts,
};
};
And use it in any component you need. For example:
const { setCurrentPage, currentPosts, amountOfPages } = usePagination(yourArrayOfData);
And for example you can use it that way(I was using Material UI Pagination component):
<Pagination
count={amountOfPages}
onChange={(event, page) => setCurrentPage(page)}
/>
And use currentPosts for actually displaying your data.
I know, that it's not direct answer to your question, but recently I have written something like you and it worked perfectly. So I hope that my solution will help you.

Add multiple files with onChange function and React Hooks, but singly

I need to add to files with react components. Here how I'm doing it with one file(onChange and onSubmit functions):
const onChangeFile = e => {
setFileData(e.target.files[0]);
};
const onSubmit = e => {
e.preventDefault();
const newItem = new FormData();
newItem.append('item', fileData);
const { description } = offerData;
newItem.append('description', description);
addItem(newItem);
setFileData(null);
}
Input(reactstrap):
<CustomInput
type="file"
name="item" id="item" label="Choose item image..."
onChange={onChangeFile}
/>
And here, how I'm doing it with multiple files, but with one input:
const onChangeFile = e => {
setFileData(e.target.files);
};
const onSubmit = e => {
e.preventDefault();
const newItem = new FormData();
for (const key of Object.keys(fileData)) {
newItem.append('item', fileData[key])
}
const { description1, description2 } = item;
newItem.append('description1', description1);
newItem.append('description2', description2);
addItem(newItem);
setFileData(null);
}
and input:
<CustomInput
type="file"
name="item"
id="item"
multiple
label="Add images/image..."
onChange={onChangeFile}
/>
And both works, but this time I want to add multiple files( two exactly), with two single inputs and my useState hook doesn't work(like that it isn't iterable). Here's how it looks like for both ways.
const [fileData, setFileData] = useState(null);
So, how to add one object with two images, but added with two single inputs?
Not sure if I fully understand. So the way you have it now you have a single input to receive data, however you want to be able to update your state from two inputs?
When you are setting state you are doing:
const onChangeFile = e => {
setFileData(e.target.files);
};
If this same handler is hooked up to another input, the second set of files will just override the first.
If you want to keep adding to your state you could either use an object, or an array. So onChange could look something like this:
const onChangeFile = e => {
// assuming here that e.target.files is an array already
const filesToAdd = e.target.files;
setFileData([...filesData, ...filesToAdd]);
};
Or with an object
const onChangeFile = e => {
const filesToAdd = e.target.files.reduce(
(map, file) => ({..., [file.name]: file}), {}));
const filesDataUpdate = {
...filesData,
...filesToAdd
}
setFileData(filesDataUpdate);
};
In this case I am assuming each file has a unique name. You could key it with any unique value.
Hope that helps!

Categories