Dynamically created custom form components in react - javascript

See this gist for the complete picture.
Basically I will have this form:
When you click the plus, another row should appear with a drop down for day and a time field.
I can create the code to add inputs to the form, however I'm having trouble with the individual components (selectTimeInput is a row) actually updating their values.
The onChange in the MultipleDayTimeInput is receiving the correct data, it is just the display that isn't updating. I extremely new to react so I don't know what is causing the display to not update....
I think it is because the SelectTimeInput render function isn't being called because the passed in props aren't being updated, but I'm not sure of the correct way to achieve that.
Thinking about it, does the setState need to be called in the onChange of the MultipleDayTimeInput and the input that changed needs to be removed from the this.state.inputs and readded in order to force the render to fire... this seems a little clunky to me...

When you update the display value of the inputs in state, you need to use this.setState to change the state data and cause a re-render with the new data. Using input.key = value is not the correct way.
Using State Correctly
There are three things you should know about
setState().
Do Not Modify State Directly
For example, this will not re-render a
component:
// Wrong
this.state.comment = 'Hello';
Instead, use setState():
// Correct
this.setState({comment: 'Hello'});
The only place where you
can assign this.state is the constructor.
read more from Facebook directly here
I would actually suggest a little bit of a restructure of your code though. It's not really encouraged to have components as part of your state values. I would suggest having your different inputs as data objects in your this.state.inputs, and loop through the data and build each of the displays that way in your render method. Like this:
suppose you have one input in your this.state.inputs (and suppose your inputs is an object for key access):
inputs = {
1: {
selectedTime: 0:00,
selectedValue: 2
}
}
in your render, do something like this:
render() {
let inputs = Object.keys(this.state.inputs).map((key) => {
let input = this.state.inputs[key]
return (<SelectTimeInput
key={key}
name={'option_' + key}
placeholder={this.props.placeholder}
options={this.props.options}
onChange={this.onChange.bind(this, key)}
timeValue={input.selectedTime}
selectValue={input.selectedValue}
/>)
)}
return (
<div>
<button className="button" onClick={this.onAddClick}><i className="fa fa-plus" /></button>
{ inputs }
</div>
);
}
Notice how we're binding the key on the onChange, so that we know which input to update. now, in your onChange function, you just set the correct input's value with setState:
onChange(event, key) {
this.setState({
inputs: Immutable.fromJS(this.state.inputs).setIn([`${key}`, 'selectedTime'], event.target.value).toJS()
// or
inputs: Object.assign(this.state.inputs, Object.assign(this.state.inputs[key], { timeValue: event.target.value }))
})
}
this isn't tested, but basically this Immutable statement is going to make a copy of this.state.inputs and set the selectedTime value inside of the object that matches the key, to the event.target.value. State is updated now, a re-render is triggered, and when you loop through the inputs again in the render, you'll use the new time value as the timeValue to your component.
again, with the Object.assign edit, it isn't tested, but learn more [here]. 2 Basically this statement is merging a new timeValue value in with the this.state.inputs[key] object, and then merging that new object in with the entire this.state.inputs object.
does this make sense?

I modified the onChange in the MultipleDayTimeInput:
onChange(event) {
const comparisonKey = event.target.name.substring(event.target.name.length - 1);
const input = this.getInputState(comparisonKey);
input.selected = event.target.value;
input.display = this.renderTimeInput(input);
let spliceIndex = -1;
for (let i = 0; i < this.state.inputs.length; i++) {
const matches = inputFilter(comparisonKey)(this.state.inputs[i]);
if (matches) {
spliceIndex = i;
break;
}
}
if (spliceIndex < 0) {
throw 'error updating inputs';
}
this.setState({
inputs: [...this.state.inputs].splice(spliceIndex, 1, input)
});
}
The key points are:
// re render the input
input.display = this.renderTimeInput(input);
// set the state by copying the inputs and interchanging the old input with the new input....
this.setState({
inputs: [...this.state.inputs].splice(spliceIndex, 1, input)
});
Having thought about it though, input is an object reference to the input in the this.state.inputs so actually [...this.states.inputs] would have been enough??

Related

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. - React

So I'm trying to make a screen where data from user's localstorage is used (Lets call it var1) but I'm getting Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. error. What I'm trying to do is check if the data from user's localstorage exists and if it does then it will put that data into a state but first it will grab another variable from localstorage (User auth token, lets call it var2) and put it into every object in var1 (var1 is a list which contains objects) and this is done using map then the state is set to the changed var1 with the auth token(or var2), then it returns some HTML and some logic is used in HTML, For every object in var1 it will create a new select tag with numbers ranging from 1 to 20 and this is done using mapping an array with 20 numbers (I'm doing this because I could not get for loop to work properly) and if the current number of option in select tag matches a key value pair in one of var1's object then it will
select the option tag or put selected attribute on option tag and if you change the value of select tag then it will trigger a function which will map through var1 and select the object which user requested and change the value of quantity to whatever the user selected on select tag. I tried to cut down and simplify my code as much as I could. My code is like this:
function RandomScreen() {
const [var1, setvar1] = useState([])
let localstoragevar = JSON.parse(localStorage.getItem('var'))
let newCart = []
if (localstoragevar) {
localstoragevar.map(item => {
item.authtoken = localStorage.getItem('AuthToken')
newCart.push(item)
})
}
setvar1(newCart)
let twenty = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
return (
{var1.map(newItem => {
{/* HTML code goes here */}
{twenty.map(number => {
if (number == item.quantity) {
return (
<option onChange={handleClick} selected name={newItem.id} value={newItem.quantity}>{newItem.quantity}</option>
)
} else {
return (
<option onChange={handleClick} name={newItem.id} value={number}>{number}</option>
)
}
})}
})}
)
}
Your render calls setvar1 which in turn trigger's a re-render.
You should put this whole logic inside a useEffect hook:
useEffect(() => {
let localstoragevar = JSON.parse(localStorage.getItem('var'))
let newCart = []
if (localstoragevar) {
localstoragevar.map(item => {
item.authtoken = localStorage.getItem('AuthToken')
newCart.push(item)
})
}
setvar1(newCart)
}, []);
This is what you have to do is to avoid logic in your render function. For that case, we do have useEffect function plus on top of that you may add useMemo;

React DatePicker loads with default value but then will not change when state changes

I have a component which renders x amount of DateInputs based on x number of charges. The date inputs should be rendered with the default value loaded from the server. Once the onChange is triggered it updates the state in the parent and prints out the console with the selected date using the computedProperty. To give more context here is an image of the page:
A you can see, a datepicker is rendered for each charge and the user needs the ability to modify the charge date. So in terms of data flow, the onChange in the child component triggers the method handleChargesDateChange in the parent, as the state needs to be stored in parent.
At the minute, the default charge date is rendered in the dropdown, but when onChange is executed then date input value does not change. However, the method prints out the correct date that was selected. Again, for more context, here is a screenshot of the data stored in parent when child executes onChange on the date picker.
As you can see, the date values get modified when the user selects one from each datepicker. However, the actual datepicker value stays the same. I can get it to work where it renders with an empty date for each datepicker and when the user selects a new date, it will render the datepicker with the selected date. It also stored the value in parent. But I am really struggling to render the defalt value, but when it is changed update the datepicker with the user selected value... I hope this makes sense.. Anyway here's the code. So the method which gets triggered in parent:
handleChargesDateChange = (e) => {
const date = e.target.value;
const momentDate = moment(date);
const chargeId = e.target.name;
console.log(date);
console.log(momentDate);
this.setState({
updatedChargeDates: [
...this.state.updatedChargeDates,
{[chargeId]: date}
]
}, () => console.log(this.state.updatedChargeDates))
}
This then gets passed down (around 3 children deep) via:
<Grid.Row>
<Grid.Column width={16}>
<OrderSummary
order={this.state.order}
fuelTypes={this.state.fuelTypes}
vehicleClasses={this.state.vehicleClasses}
deviceTypes={this.state.deviceTypes}
chargeTypes={this.state.chargeTypes}
featureTypes={this.state.featureTypes}
itemGroups={this.state.itemGroups}
itemTypes={this.state.itemTypes}
updateChargeDates={this.handleChargesDateChange}
chargeDates={this.state.updatedChargeDates}
/>
</Grid.Column>
I will skip the various other children components that the method gets passed to and go straight to the effected component. So the method then lands at Charges:
export class Charges extends Component {
constructor(props) {
super(props);
this.state = {
currentItem: 0,
newDate: '',
fields: {}
}
}
render() {
const {charges, chargeTypes, updateChargeDates, chargeDates} = this.props;
console.log('Props method', charges);
if (charges.length === 0) { return null; }
return <Form>
<h3>Charges</h3>
{charges.map(charge => {
console.log(charge);
const chargeType = chargeTypes.find(type => type.code === charge.type) || {};
return <Grid>
<Grid.Row columns={2}>
<Grid.Column>
<Form.Input
key={charge.id}
label={chargeType.description || charge.type}
value={Number(charge.amount).toFixed(2)}
readOnly
width={6} />
</Grid.Column>
<Grid.Column>
<DateInput
name={charge.id}
selected={this.state.newDate}
***onChange={updateChargeDates}***
***value={chargeDates[charge.id] == null ? charge.effectiveDate : chargeDates[charge.id]}***
/>
</Grid.Column>
</Grid.Row>
</Grid>
})}
<Divider hidden />
<br />
</Form>
}
I have highlighted the culprit code with *** to make it easier to follow. I am using a ternary type operator to determine which value to display, but it doesnt seem to update when i select a value.. I thought that from the code I have, if the initial chargeDates[charge.id] is null then we display the charge.effectiveDate which is what it is doing, but soon as I change the date i would expect chargeDates[charge.id] to have a value, which in turn should display that value...
I really hope that makes sense, im sure im missing the point with this here and it will be a simple fix.. But seems as im a newbie to react, im quite confused..
I have tride to follow the following resources but it doesnt really give me what I want:
Multiple DatePickers in State
Daepicker state
If you need anymore questions or clarification please do let me know!
Looking at your screenshot, updatedChargeDates (chargeDates prop) is an array of objects. The array has indexes 0, 1 and 2, but you access it in the DateInput like this chargeDates[charge.id] your trying to get the data at the index 431780 for example, which returns undefined, and so the condition chargeDates[charge.id] == null ? charge.effectiveDate : chargeDates[charge.id], will always return charge.effectiveDate.
You can fix this in handleChargesDateChange by making updatedChargeDates an object, like this :
handleChargesDateChange = (e) => {
const date = e.target.value;
const momentDate = moment(date);
const chargeId = e.target.name;
console.log(date);
console.log(momentDate);
this.setState({
updatedChargeDates: {
...this.state.updatedChargeDates,
[chargeId]: date
}
}, () => console.log(this.state.updatedChargeDates))
}

Why is useState not triggering re-render?

I've initialized a state that is an array, and when I update it my component does not re-render. Here is a minimal proof-of-concept:
function App() {
const [numbers, setNumbers] = React.useState([0, 1, 2, 3]);
console.log("rendering...");
return (
<div className="App">
{numbers.map(number => (
<p>{number}</p>
))}
<input
type="text"
value={numbers[0].toString()}
onChange={newText => {
let old = numbers;
old[0] = 1;
setNumbers(old);
}}
/>
</div>
);
}
Based on this code, it seems that the input should contain the number 0 to start, and any time it is changed, the state should change too. After entering "02" in the input, the App component does not re-render. However, if I add a setTimeout in the onChange function which executes after 5 seconds, it shows that numbers has indeed been updated.
Any thoughts on why the component doesn't update?
Here is a CodeSandbox with the proof of concept.
You're calling setNumbers and passing it the array it already has. You've changed one of its values but it's still the same array, and I suspect React doesn't see any reason to re-render because state hasn't changed; the new array is the old array.
One easy way to avoid this is by spreading the array into a new array:
setNumbers([...old])
You need to copy numbers like so let old = [...numbers];
useState doesn't update the value only if it has changed so if it was 44 and it became 7 it will update. but how can it know if an array or object have changed. it's by reference so when you do let old = numbers you are just passing a reference and not creating a new one
Others have already given the technical solution. To anyone confused as to why this happens, is because setSomething() only re renders the component if and only if the previous and current state is different. Since arrays in javascript are reference types, if you edit an item of an array in js, it still doesn't change the reference to the original array. In js's eyes, these two arrays are the same, even though the original content inside those arrays are different. That's why setSomething() fails do detect the changes made to the old array.
Note that if you use class components and update the state using setState() then the component will always update regardless of whether the state has changed or not. So, you can change your functional component to a class component as a solution. Or follow the answers provided by others.
You can change state like this
const [state, setState] = ({})
setState({...state})
or if your state is Array you can change like this
const [state, setState] = ([])
setState([...state])
I was working on an array that had objects in it and I tried few of the above.
My useState is :
const [options, setOptions] = useState([
{ sno: "1", text: "" },
{ sno: "2", text: "" },
{ sno: "3", text: "" },
{ sno: "4", text: "" },
]);
Now I want to add more options with blank field on a click of a button I will use the following way to achieve my purpose:
<button
onClick={() => {
setOptions([...options, { sno: newArray.length + 1, text: "" }]);
}}
>
This solved my problem and I was able to re render the component and added an object to the array.
introduces an array of the component that is not the one of the hook. for instance:
const [numbers, setNumbers] = useState([0, 1, 2, 3]);
var numbersModify = []; //the value you want
and at the end:
setNumbers(numbersModify)
modify this numbersModify, when the hook refreshes it will return to 0 numbersModify and the hook will keep the state. Therefore, the problem of not seeing the changes will be eliminated.
:D
//define state using useState hook
const [numbers, setNumbers] = React.useState([0, 1, 2, 3]);
//copy existing numbers in temp
let tempNumbers = [...numbers];
// modify/add no
tempNumbers.push(4);
tempNumbers[0] = 10;
// set modified numbers
setNumbers(tempNumbers);
I dont have any proud of this but it works
anotherList = something
setSomething([])
setTimeout(()=>{ setSomething(anotherList)},0)
useState is a React hook which provides functionality of having State in a functional component.
Usually it informs React to re-render the component whenever there is change in useState variables.
{
let old = numbers;
old[0] = 1;
setNumbers(old);
}
In the above code since you are referring to the same variable it stores the reference not the value hence React doesn't know about the latest changes as the reference is same as previous.
To overcome use the below hack, which will not copy the reference instead it's a deep copy(copies the values)
{
let old = JSON.parse(JSON.stringify(numbers));
old[0] = 1;
setNumbers(old);
}
Happy coding :)

The value of one input is affecting another

I have a simple app which allows someone to add a numbers into an input, and have those numbers render onto the page (as inputs) which can be edited.
addSiblingValue(evt) {
this.setState({
currentObject: {
...this.state.currentObject,
numberOfSiblings: evt.target.value
}
});
add() {
const array = [...this.state.array, this.state.currentObject];
this.setState({
array
});
}
siblingCountChange(rowIndex, event) {
const array = [...this.state.array];
array[rowIndex].numberOfSiblings = event.target.value;
this.setState({ array });
}
So when I add a number it renders a new input with the value set to the number I've just added, but when I go to change that value, it now is affecting the first input.
The first row of inputs are using their own object currentObject which pushes to to the this.state.array, so I'm not sure why editing anything in that array would affect the currentObject?
Expected behaviour:
User enters a number into the input and clicks add
That input is rendered and can be edited independently
How do I achieve this or what is it I'm doing wrong here?
CodeSandbox
Thank you
When you add this.state.currentObject to the array, it works as an reference, so that the added object in the array and this.state.currentObject are the same object. You can prevent that by adding not the object itself, but a copy of the object into the array:
add() {
const array = [...this.state.array, {"numberOfSiblings": this.state.currentObject.numberOfSiblings}];
this.setState({
array
});
}
siblingCountChange(rowIndex, event) {
const array = [...this.state.array];
array[rowIndex].numberOfSiblings += parseInt(event.target.value);
this.setState({ array });
}
You were not adding the actual number to the current state. I also removed the value from the add like so:
<input
type="text"
onChange={this.siblingCountChange.bind(this, rowIndex)}
/>
You will need to put error handling on the state as a string plus a number leads to NaN error. As you can see the number is parsed before addition.
Thanks to dieckie for pointing me in the right direction. Unfortunately that particular solution did not work, but using Object.assign to create a reference and pushing that to the array did?
Posting here so it helps others/myself in future:
add() {
let copyOfCurrentObject = Object.assign({}, this.state.currentObject);
const array = [...this.state.array, copyOfCurrentObject];
this.setState({
array
})
}
This question was also helpful.

slice happens in the code but it doesnt update in the UI

there are three drop down menus in the initial state.
after I select the first drop down the second drop down values gets loaded
after I select the second drop down values.
a new set of drop down loads.
when I select remove button of the second set.
it doesnt remove that set but it removes the first set.
when I debugged removeSelectedValue method there slices are happening correctly but its not updating in the updating
can you tell me how to pass the queryComponents values so that it will update in the UI.
can you tell me how to fix it.
so that in future I will fix it myself.
providing my relevant code snippet and sandbox below.
all my code is in demo.js
https://codesandbox.io/s/4x9lw9qrmx
removeSelectedValue = index => {
console.log("removeSelectedValue--->", index);
let seletedValues = this.state.queryComponents;
seletedValues.splice(index, 1);
console.log("spliced Values--->", seletedValues);
this.setState({ queryComponents: seletedValues });
};
render() {
let queryComp = this.state.queryComponents.map((value, index) => {
return (
<AutoCompleteComponent
key={index}
value={value}
index={index}
valueSelected={this.getSelectedValue}
removeSeleted={this.removeSelectedValue}
/>
);
});
return <div>{queryComp}</div>;
}
When you do let seletedValues = this.state.queryComponents;
you're creating a reference to that variable, instead of making a copy.
You need to make sure you replace your state with a new object/array for the re-render to happen.
Please try this:
removeSelectedValue = index => {
this.setState(prevState => ({
queryComponents: prevState.seletedValues.filter((a, i) => (i !== index));
});
};
That filter function is equivalent to the splice you were using, but returns a new array instead of modifying the original one.
On the other hand, I 'm passing setState a function that uses prevState making the code shorter.

Categories

Resources