reactjs setState not changing state - javascript

I have a function(onClickAddSection), when its called, it should set the state to empty string but it doesn't do that at all.
Please take a look at the code and tell me what im doing wrong thank you.
class AddNewSectionForm extends Component {
constructor(props) {
super(props);
this.state = {
sectionName: '',
validation:false
};
this.onSectionNameChange = this.onSectionNameChange.bind(this);
this.onClickAddSection = this.onClickAddSection.bind(this);
}
onSectionNameChange(event) {
if(this.state.validation==false){
this.setState({validation:true});
}
this.setState({sectionName: event.target.value});
}
onClickAddSection(event) {
event.preventDefault();
this.props.saveSection(this.state.sectionName);
this.setState({sectionName:'',validation:false});
}
render() {
return (
<div>
<TextInput name="newSection" label="Section Name :"
onChange={this.onSectionNameChange}
value={this.state.sectionName}
error = {this.state.validation==true&& this.state.sectionName.length==0?'Enter Section Name':''}/>
<AddCloseButtons add = {this.onClickAddSection}
close = {this.props.closeCharm}
/>
</div>
);
}
}
the onClickAddSection function doesn't set the sectionName back to ''.
AddCloseButton:
const AddCloseButtons = ({add,close}) => {
return (
<div className="form-group">
<button className="btn btn-primary" style={{width: '40%', border:'solid black 1px'}} onClick={add}>Add</button>
<button className="btn btn-secondary" style={{width: '40%', float: 'right',border:'solid black 1px'}} onClick={close}>Close</button>
</div>);
};

Are you using Redux? if so, this.props.saveSection makes any Ajax Call?. If so, could be that you update the local state with setState and then your Ajax response re updates it the received value?

Just try and see the functional version of setState.
this.setState(function (state, props) {
return {
sectionName:'',
validation:false
}
});

It seems that when you click the button, onSectionNameChange and onClickAddSection happen at the same time and will have conflict (because the name is set to blank means its name is being changed ^^), so how about not setting state for sectionName in onSectionNameChange:
onSectionNameChange(event) {
if(this.state.validation==false){
this.setState({validation:true});
}
//this.setState({sectionName: event.target.value});
}
I guess so, please post here some errors if any, thanks

Related

Problem with the confirmation button. The Button does not work

I have created a button that saves the entered data, however when I click on it, nothing happens.Here is the code.
class DefinesPagePresenter extends Component {
constructor(props) {
super(props);
this.state = {
isNeedOpenInfoWindow: false,
filesContentDict: {
[props.iniType]: props.json
}
};
}
onChange = () => {
if (this.state.filesContentDict[this.props.iniType]) {
this.props.changeInitFileParams(this.props.market, this.props.iniType, this.state.filesContentDict[this.props.iniType]);
this.setState({ isNeedOpenInfoWindow: true });
}
}
<form onSubmit={(e) => {
e.preventDefault()
this.onChange()
}}>
<div height="200%" style={{
margin: '20px 0px 0px 40px'
}}><input type="submit" value="Ok" className="c4t-button" height="200%" size="50px" /></div>
</form>
The following similar snippet to your code shows that the alert does run when clicking on the <input type='submit' /> without seeing your code there could be other problems or this.state is not what you think it is within that function (improper scoping or just at the time it is false so it doesn't run what is within the if statement).
I suggest you have an else { for the event Handler which you called onChange: so you can see if that's triggered for example it seems like you are waiting for a prop named json= to be filled in and maybe it is not when you try clicking. You might consider disabling the button until this.props.json is there.
onChange = () => {
if (this.state.filesContentDict[this.props.iniType]) {
//also make sure this method is actually running
console.log('about to run: changeInitFileParams')
this.props.changeInitFileParams(this.props.market, this.props.iniType, this.state.filesContentDict[this.props.iniType]);
this.setState({ isNeedOpenInfoWindow: true });
}
else {
alert('JSON Was not yet loaded')
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isNeedOpenInfoWindow: false,
filesContentDict: {
[props.iniType]: props.json
}
};
}
onConfirm = () => {
if (this.state.filesContentDict[this.props.iniType]) {
this.props.alertInputs(JSON.stringify({
statement: this.state.filesContentDict[this.props.iniType].statement,
iniType: this.props.iniType
}, null, 4))
this.setState({
isNeedOpenInfoWindow: true
}, console.log) // should reflect the state immediately after change
}
else {
alert('false')
}
}
render() {
return (
<form
style={{ background: 'green', height: 300 }}
onSubmit={(e) => {
e.preventDefault();
this.onConfirm();
}}
>
<input
type='submit'
value='Ok'
/>
{this.state.isNeedOpenInfoWindow &&
<div style={{
display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '6rem' }}>
<div>
iniType:<br />
statement: <br />
</div>
<div>
{this.props.iniType} <br />
{this.state.filesContentDict[this.props.iniType].statement}
</div>
</div>
}
</form>
);
}
}
ReactDOM.render(
<App
iniType='load'
alertInputs={inputs => alert(inputs)}
json={{ statement: 'The quick Brown Fox jumped over the lazy dog!' }}
/>,
window.root
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>
I find it a bit strange (but I'm not sure what the exact situation is with your props) that it seems like you send the changeInitFileParams to an outer/parent React Component and then change the state of this child to isNeedOpenInfoWindow it would make more sense to change that state to the parent in most situations if the parent needs the changeInitFileParams to run.
In short nothing is not going to work with any of the code you're actually shown (I proved that it works all the functions get called) and the alert shows up. Whatever is not working is not displayed here: I'd be most suspicious about json={neverBeingDefined} or isNeedOpenInfoWindow being on this Component's state vs on the parent. (Assuming the render(){ method returns that form and some sort window that needs the state: isNeedOpenInfoWindow.
I think you should change your from onSubmit like this
onsubmit={(event)=> onChange(event)}
then use this code on onChange =>
const onChange = (event) => {
e.preventDefault();
if (this.state.filesContentDict[this.props.iniType]) {
this.props.changeInitFileParams(this.props.market, this.props.iniType,
this.state.filesContentDict[this.props.iniType]);
this.setState({ isNeedOpenInfoWindow: true });
}
}
The main reason you getting error because you are not using button. You are using input tag.
Change
<button type="submit" className="c4t-button" height="200%" size="50px">Ok</button>

Why am I getting an error here? React Todo list

I am trying to create a todo list using React but i cant seem to understand why I am getting the error: "Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state."
Here's the code:
import React from 'react'
import ReactDOM from 'react-dom'
class Todo extends React.Component{
constructor(props){
super(props)
this.state = {
input: '',
list: []
}
this.handleChange = this.handleChange.bind(this)
this.reset = this.reset.bind(this)
this.removeItem = this.removeItem.bind(this)
this.add = this.add.bind(this)
}
add(){ //Adds a new task
const newItem = {
value: this.state.input,
id: Math.random + Math.random
};
const listed = [...this.state.list]
listed.push(newItem)
this.setState({
input: '',
list: listed
})
}
removeItem(id){ //deletes a task
const list = [...this.state.list]
const updatedList = list.filter(obj => {
return obj.id !== id
})
this.setState({
list: updatedList
})
}
handleChange(e){
this.setState({input: e.target.value})
}
reset(e){
e.preventDefault()
}
render(){
return (
<div>
<form action="" onSubmit={this.reset}>
<input type="text" value={this.state.input} placeholder='Enter a task..' onChange={this.handleChange} />
<button onClick={this.add}>Add Task</button>
{this.state.list.map(item => { //updates when a task is added or removed
return (
<div key={item.id}>
<h1>{item.value}</h1>
<button onClick={this.removeItem(item.id)}>X</button>
</div>
)
})}
</form>
</div>
)
}
}
ReactDOM.render(<Todo />,document.getElementById('root'))
Because you are calling removeItem on render. It needs to be wrapped in a separate function:
<button onClick={() => this.removeItem(item.id)}>X</button>
So that you only call it onClick and not on render.
<button onClick={this.removeItem(item.id)}>X</button>
In this button the event handler you have provided runs immediately due to the presents of the () at the end. To prevent this and still provide your argument item.id you can enclose the handler this.removeItem(item.id) with in another function.
I like the arrow function for this so mine looks like this
<button onClick={ ()=>this.removeItem(item.id) }>X</button>.
Math.random + Math.random is not returning a number like you would want for the element key. This is because your have neglected to include () at telling JS to run the function and return an int.
After making these changes, I ran it in codepen.io and it seemed to work fine.

Save textarea value to div with ReactJs

I'm only trying to deal with the React, so my question may seem very simple, but still I'm stuck on it.
I have two blocks (div.user-data__row) in which there are some values. I change the state of the component (handleChange function), the state in which these blocks are replaced by text fields (textarea.text), and I want when I click on the save button and call saveChange function, the value from each text field is taken and passed to the blocks (1st textarea to 1st block, etc).
I found examples of solving a similar case using the ref attribute, but later read that this is no longer an actual solution and so no one does. Please help me find the actual implementation path.
class UserData extends React.Component {
constructor(props) {
super(props);
this.state = {
edit: true,
};
this.handleChange = this.handleChange.bind(this);
this.saveChange = this.handleChange.bind(this);
}
handleChange() {
this.setState(() => ({
edit: !this.state.edit,
}));
}
saveChange() {
this.setState(() => ({
edit: false
}))
}
render() {
if (this.state.edit) {
return (
<div className="user-data">
<div className="user-data__row">{this.props.userData.name}</div>
<div className="user-data__row">{this.props.userData.email}</div>
<button onClick={ this.handleChange }>Edit</button>
</div>
);
} else {
return (
<div className="user-data">
<textarea className="text" defaultValue={this.props.userData.name}></textarea>
<textarea className="text" defaultValue={this.props.userData.email}></textarea>
<button onClick={ this.saveChange }>Save</button>
</div>
)
}
}
}
Because props are read-only & because userData (email+name) can be changed inside the component , you have to populate props values in the state, then manage the state after that will be enough.
Also , you will need to convert your textarea from uncontrolled component to controlled component by:
Using value instead of defaultValue
Implementing onChange with setState of that value as handler .
Value of textarea should be read from state not props.
If props of <UserData /> may be updated from outside throughout its lifecycle , you will need componentWillReceiveProps later on.
Also you have a typo if (!this.state.edit) { and not if (this.state.edit) { .
class UserData extends React.Component {
state = {
edit: true,
userDataName: this.props.userData.name, // Populate props values
userDataEmail: this.props.userData.email, // Populate props values
};
handleChange = () => {
this.setState((state) => ({
edit: !state.edit,
}));
}
saveChange =() => {
this.setState(() => ({
edit: false
}))
}
render() {
if (!this.state.edit) {
return (
<div className="user-data">
<div className="user-data__row">{this.state.userDataName}</div>
<div className="user-data__row">{this.state.userDataEmail}</div>
<button onClick={ this.handleChange }>Edit</button>
</div>
);
} else {
return (
<div className="user-data">
<textarea className="text" value={this.state.userDataName} onChange={(e) => this.setState({userDataName: e.target.value})}></textarea>
<textarea className="text" value={this.state.userDataEmail} onChange={(e) => this.setState({userDataEmail: e.target.value})}></textarea>
<button onClick={ this.saveChange }>Save</button>
</div>
)
}
}
}
ReactDOM.render(<UserData userData={{name: 'Abdennoor', email: 'abc#mail.com'}} /> , document.querySelector('.app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div class="app" />
You're receiving values for <div> from this.props, it means that these values should came from some external source and passed to your component. A way of passing these values to component's props is out of scope of this question, it can be implemented in a very different ways. Usually it came either from parent component or from some connected store.
You need to obtain values from your <textarea> form fields, it can be done directly (using ref) or by using some third-party library that provides form handling. Then these values needs to be stored (and obtained) either directly from component's state or from external source (via props).
Unfortunately scope of your question is too broad to be able to give more precise answer, but hope that this information will lead you to some kind of solution.
You can also use contentEditable, which it will allow you to edit the content of the div.
class UserData extends React.Component {
constructor(props) {
super(props);
this.state = {
edit: true
};
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.setState(() => ({
edit: !this.state.edit
}));
}
render() {
const { edit } = this.state;
return (
<div className="user-data">
<div className="user-data__row" contentEditable={edit}>{this.props.userData.name}</div>
<div className="user-data__row" contentEditable={edit}>{this.props.userData.email}</div>
<button onClick={this.handleChange}>
{edit ? Save : Edit}
</button>
</div>
)
}
}

setState being called too late

I am trying to make a text box auto focus.
However, I the setState is being called too late it seems.
It is being called within Popup.show. I created a button to console.log the state, and it does seem to be set to true but it must happen too late.
How can I get setState to be called as the Popup.show happens?
class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
focused: false,
};
}
onClick = (event) => {
console.log('Says focussed FALSE', this.state.focused)
this.setState({ focused:true });
Popup.show(<div>
<SearchBar
autoFocus
focused={this.state.focused}
/>
<button onClick={this.checkState}>It says TRUE here</button>
</div>,
console.log('Says focussed FALSE still', this.state.focused),
{ animationType: 'slide-up'});
};
checkState = (e) =>{
console.log(this.state)
}
render() {
return (
<div style={{ padding: '0.15rem' }}>
<Button onClick={this.onClick.bind(this)}>Open & Focus</Button>
</div>);
}
}
Always remember that setState won't execute immediately. If you want Popup.show() after setState, you can use a callback:
this.setState({ focused: true }, () => {
Popup.show(...)
})
And you are already using arrow functions, you don't need the .bind(this) in your render function.
setState doesn't immediate set the state
From: https://facebook.github.io/react/docs/react-component.html#setstate
Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
Changing your setState to something like
this.setState({ focused: true }, () => {
Popup.show(<div>
<SearchBar
autoFocus
focused={this.state.focused}
/>
<button onClick={this.checkState}>It says TRUE here</button>
</div>)
});

ReactJs: Prevent multiple times button press

In my React component I have a button meant to send some data over AJAX when clicked. I need to happen only the first time, i.e. to disable the button after its first use.
How I'm trying to do this:
var UploadArea = React.createClass({
getInitialState() {
return {
showUploadButton: true
};
},
disableUploadButton(callback) {
this.setState({ showUploadButton: false }, callback);
},
// This was simpler before I started trying everything I could think of
onClickUploadFile() {
if (!this.state.showUploadButton) {
return;
}
this.disableUploadButton(function() {
$.ajax({
[...]
});
});
},
render() {
var uploadButton;
if (this.state.showUploadButton) {
uploadButton = (
<button onClick={this.onClickUploadFile}>Send</button>
);
}
return (
<div>
{uploadButton}
</div>
);
}
});
What I think happens is the state variable showUploadButton not being updated right away, which the React docs says is expected.
How could I enforce the button to get disabled or go away altogether the instant it's being clicked?
The solution is to check the state immediately upon entry to the handler. React guarantees that setState inside interactive events (such as click) is flushed at browser event boundary. Ref: https://github.com/facebook/react/issues/11171#issuecomment-357945371
// In constructor
this.state = {
disabled : false
};
// Handler for on click
handleClick = (event) => {
if (this.state.disabled) {
return;
}
this.setState({disabled: true});
// Send
}
// In render
<button onClick={this.handleClick} disabled={this.state.disabled} ...>
{this.state.disabled ? 'Sending...' : 'Send'}
<button>
What you could do is make the button disabled after is clicked and leave it in the page (not clickable element).
To achieve this you have to add a ref to the button element
<button ref="btn" onClick={this.onClickUploadFile}>Send</button>
and then on the onClickUploadFile function disable the button
this.refs.btn.setAttribute("disabled", "disabled");
You can then style the disabled button accordingly to give some feedback to the user with
.btn:disabled{ /* styles go here */}
If needed make sure to reenable it with
this.refs.btn.removeAttribute("disabled");
Update: the preferred way of handling refs in React is with a function and not a string.
<button
ref={btn => { this.btn = btn; }}
onClick={this.onClickUploadFile}
>Send</button>
this.btn.setAttribute("disabled", "disabled");
this.btn.removeAttribute("disabled");
Update: Using react hooks
import {useRef} from 'react';
let btnRef = useRef();
const onBtnClick = e => {
if(btnRef.current){
btnRef.current.setAttribute("disabled", "disabled");
}
}
<button ref={btnRef} onClick={onBtnClick}>Send</button>
here is a small example using the code you provided
https://jsfiddle.net/69z2wepo/30824/
Tested as working one: http://codepen.io/zvona/pen/KVbVPQ
class UploadArea extends React.Component {
constructor(props) {
super(props)
this.state = {
isButtonDisabled: false
}
}
uploadFile() {
// first set the isButtonDisabled to true
this.setState({
isButtonDisabled: true
});
// then do your thing
}
render() {
return (
<button
type='submit'
onClick={() => this.uploadFile()}
disabled={this.state.isButtonDisabled}>
Upload
</button>
)
}
}
ReactDOM.render(<UploadArea />, document.body);
You can try using React Hooks to set the Component State.
import React, { useState } from 'react';
const Button = () => {
const [double, setDouble] = useState(false);
return (
<button
disabled={double}
onClick={() => {
// doSomething();
setDouble(true);
}}
/>
);
};
export default Button;
Make sure you are using ^16.7.0-alpha.x version or later of react and react-dom.
Hope this helps you!
If you want, just prevent to submit.
How about using lodash.js debounce
Grouping a sudden burst of events (like keystrokes) into a single one.
https://lodash.com/docs/4.17.11#debounce
<Button accessible={true}
onPress={_.debounce(async () => {
await this.props._selectUserTickets(this.props._accountId)
}, 1000)}
></Button>
If you disable the button during onClick, you basically get this. A clean way of doing this would be:
import React, { useState } from 'react';
import Button from '#material-ui/core/Button';
export default function CalmButton(props) {
const [executing, setExecuting] = useState(false);
const {
disabled,
onClick,
...otherProps
} = props;
const onRealClick = async (event) => {
setExecuting(true);
try {
await onClick();
} finally {
setExecuting(false);
}
};
return (
<Button
onClick={onRealClick}
disabled={executing || disabled}
{...otherProps}
/>
)
}
See it in action here: https://codesandbox.io/s/extended-button-that-disabled-itself-during-onclick-execution-mg6z8
We basically extend the Button component with the extra behaviour of being disabled during onClick execution. Steps to do this:
Create local state to capture if we are executing
Extract properties we tamper with (disabled, onClick)
Extend onClick operation with setting the execution state
Render the button with our overridden onClick, and extended disabled
NOTE: You should ensure that the original onClick operation is async aka it is returning a Promise.
By using event.target , you can disabled the clicked button.
Use arrow function when you create and call the function onClick. Don't forget to pass the event in parameter.
See my codePen
Here is the code:
class Buttons extends React.Component{
constructor(props){
super(props)
this.buttons = ['A','B','C','D']
}
disableOnclick = (e) =>{
e.target.disabled = true
}
render(){
return(
<div>
{this.buttons.map((btn,index) => (
<button type='button'
key={index}
onClick={(e)=>this.disableOnclick(e)}
>{btn}</button>
))}
</div>
)}
}
ReactDOM.render(<Buttons />, document.body);
const once = (f, g) => {
let done = false;
return (...args) => {
if (!done) {
done = true;
f(...args);
} else {
g(...args);
}
};
};
const exampleMethod = () => console.log("exampleMethod executed for the first time");
const errorMethod = () => console.log("exampleMethod can be executed only once")
let onlyOnce = once(exampleMethod, errorMethod);
onlyOnce();
onlyOnce();
output
exampleMethod executed for the first time
exampleMethod can be executed only once
You can get the element reference in the onClick callback and setAttribute from there, eg:
<Button
onClick={(e) => {
e.target.setAttribute("disabled", true);
this.handler();
}}
>
Submit
</Button>
Keep it simple and inline:
<button type="submit"
onClick={event => event.currentTarget.disabled = true}>
save
</button>
But! This will also disable the button, when the form calidation failed! So you will not be able to re-submit.
In this case a setter is better.
This fix this set the disabled in the onSubmit of the form:
// state variable if the form is currently submitting
const [submitting, setSubmitting] = useState(false);
// ...
return (
<form onSubmit={e => {
setSubmitting(true); // create a method to modify the element
}}>
<SubmitButton showLoading={submitting}>save</SubmitButton>
</form>
);
And the button would look like this:
import {ReactComponent as IconCog} from '../../img/icon/cog.svg';
import {useEffect, useRef} from "react";
export const SubmitButton = ({children, showLoading}) => {
const submitButton = useRef();
useEffect(() => {
if (showLoading) {
submitButton.current.disabled = true;
} else {
submitButton.current.removeAttribute("disabled");
}
}, [showLoading]);
return (
<button type="submit"
ref={submitButton}>
<main>
<span>{children}</span>
</main>
</button>
);
};
Another approach could be like so:
<button onClick={this.handleClick} disabled={isLoading ? "disabled" :""}>Send</button>
My approach is if event on processing do not execute anything.
class UploadArea extends React.Component {
constructor(props) {
super(props)
this.state = {
onProcess:false
}
}
uploadFile() {
if (!this.state.onProcess){
this.setState({
onProcess: true
});
// then do your thing
this.setState({
onProcess: false;
});
}
}
render() {
return (
<button
type='submit'
onClick={() => this.uploadFile()}>
Upload
</button>
)
}
}
ReactDOM.render(<UploadArea />, document.body);
Try with this code:
class Form extends React.Component {
constructor() {
this.state = {
disabled: false,
};
}
handleClick() {
this.setState({
disabled: true,
});
if (this.state.disabled) {
return;
}
setTimeout(() => this.setState({ disabled: false }), 2000);
}
render() {
return (
<button type="submit" onClick={() => this.handleClick()} disabled={this.state.disabled}>
Submit
</button>
);
}
}
ReactDOM.render(<Form />, document.getElementById('root'));

Categories