Double setState method in one function - javascript

I am trying to create a autocomplete component. It's an input where user types the countru name and if letters match name of some country, the hints are displayed.
In my App Component i have method handleChange Within this method i change my state two times, which is bad idea.
How can I split it to change state in distinct methods ?
import React, { Component } from 'react';
import AutoComplete from './autoComplete.jsx';
import data from './data.json';
class App extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
resoults: []
}
}
handleChange() {
let inputValue = this.refs.input.value;
this.setState({
inputValue: inputValue
});
let regular = "^" + this.state.inputValue;
let reg = new RegExp(regular , "i");
let filtered = data.filter((i,index)=> {
return (reg.test(i.name)
);
});
console.log(filtered);
this.setState({resoults:filtered})
}
render() {
return (
<div>
<input onChange={this.handleChange.bind(this)} type="text" ref="input"/>
<h3>You typed: {this.state.inputValue}</h3>
<AutoComplete resoults={this.state.resoults} />
</div>
);
}
}
export default App;
import React, {Component} from 'react';
class AutoComplete extends Component {
render() {
return (
<div>
<h4>autocompleteComponent</h4>
{this.props.resoults.map((i)=> {
return (
<ul>
<li>{i.name}</li>
</ul>
);
})}
</div>
);
}
}
export default AutoComplete;

I found myself in this position many times, but I got to the conclusion that it's better to compute the autocomplete options (in your case) without having them in the state of your component.
As I have used them until now, the state and props of a component should represent minimal data needed to render that specific component. Since you have your input value in the state, having the autocomplete options there also seems redundant to me. So here is what I propose:
class App extends Component {
this.state = {
inputValue: '',
};
handleChange(e) {
const inputValue = e.target.value;
this.setState({
inputValue,
});
}
computeResults() {
const {inputValue} = this.state;
// your functionality for computing results here
}
render() {
const {inputValue} = this.state;
const results = this.computeResults();
return (
<div>
<input type="text" onChange={this.handleChange.bind(this)} value={inputValue} />
<h2>You typed: {inputValue}</h2>
<Autocomplete results={results} />
</div>
);
}
}
Notes
Since your results come synchronously, via the .json import, this seems the perfect solution to me. If you want to get them via fetch or anything else, then you'll have to figure out a slightly different approach, but keep in mind that the state of your component should not contain redundant data.
Stop using ref with string value! and use refs when there is absolutely no other way because a React component should not generally deal with DOM operations directly. If you really need to use refs, use ref callbacks.
Hope this helps!

Use another function and setState callBack:
handleChange() {
let inputValue = this.refs.input.value;
this.setState(
{
inputValue: inputValue
},
() => this.secondFunc()
);
}
secondFunc() {
let regular = '^' + this.state.inputValue;
let reg = new RegExp(regular, 'i');
let filtered = data.filter((i, index) => {
return reg.test(i.name);
});
console.log(filtered);
this.setState({ resoults: filtered });
}

Related

React put query string into form's value attribute

I have a search page, something/search?q=foo, whenever im at this page I want to put foo in my form's value tag. (Not for search purposes, I have a fully functioning search bar, I just want to show the client the last thing he searched for).
I've gotten the search term with: (window.location.href.indexOf("?q") != -1) ? window.location.href.substring(window.location.href.indexOf("?q") + 3) : '', this works, although when putting it into the forms value tag, react blocks immediately, it doesn't let me write anything into the input field. I think this is because it updates to this string super fast and you don't see it happening.
How would I achieve this, to update my form's value one time and thats it?
Here is my simplified code:
<input type="search" name="q" id="q" value={(window.location.href.indexOf("?q") != -1) ? window.location.href.substring(window.location.href.indexOf("?q") + 3) : ''} <--- This is where I want to put the search string
What i've tried so far is this:
this.state = {
value:''
}
...
handleTitle = (s) => {
this.setState({value:s})
}
...
<input ... value={this.state.value} onChange={this.HandleTitle((window.location.href.indexOf("?q") != -1) ? window.location.href.substring(window.location.href.indexOf("?q") + 3) : '')}
this results in infinite state updates
I would suggest you get the value of the search-param when the component mounts, and store it in the component's local state. Then read/update the value from state. Something like:
const [search, setSearch] = useState("");
useEffect(() => {
setSearch(new URLSearchParams(new URL(window.location.href).search).get('q'));
}, []);
return (
<intput type="text" value={search} onChange={e => setSearch(e.target.value)} />
);
I've not tested it, but you get the gist of it.
Anyway if you want to access the q natively.
Working example
https://8zwht.csb.app/?q=test
import React from "react";
import "./styles.css";
class App extends React.Component {
state = {
value: ""
};
componentDidMount() {
const search = new URL(window.location).searchParams;
const term = search.get("q");
if (term)
this.setState({
value: term
});
}
handleChange = (e) => {
this.setState({
value: e.target.value
});
};
render() {
return (
<input
type="text"
onChange={this.handleChange}
value={this.state.value}
/>
);
}
}
export default App;
It would be easier to provide a more concrete answer if you share the code or gist

React-select defaultValues

i have a select menu with defaultValue is null
when i pass props to it , it dosent rerender with the new props as defaultValues
ps : the select is multi
i tried to use component will recieve props and everything that i find but still dosent work
this is my select component :
import React, { useState, useEffect } from "react";
import Select from "react-select";
class SelectMenu extends React.Component {
state = {
defaultValues: [],
};
componentWillReceiveProps(newProps) {
this.setState({ defaultValues: newProps.defaultValue });
}
render() {
return (
<Select
options={this.props.options}
closeMenuOnSelect={this.props.closeMenuOnSelect}
components={this.props.components}
isMulti={this.props.isMulti}
onChange={(e) => this.props.onChange(e, this.props.nameOnState)}
placeholder={this.props.default}
defaultValue={this.state.defaultValues}
/>
);
}
}
export default SelectMenu;
componentWillReceiveProps won't be called during mounting.
React doesn’t call UNSAFE_componentWillReceiveProps() with initial props during mounting. It only calls this method if some of component’s props may update. (https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops)
Also, componentWillReceiveProps is deprecated and will be removed in React 17. Take a look at getDerivedStateFromProps instead, and especially the notes on when you do not need it.
I beleive that in your case using the constructor will be perfectly fine, something like:
class Components extends React.Component {
constructor(props) {
super(props)
this.state = { some_property: props.defaultValue }
}
}
i find a solution for this problem
by using components will recieve props
and setting my state with the comming props
and in the render you need to do condition to render the select menu only if the state.length !== 0
i posted this answer just in case someone face the same problem i know its not the most optimal solution but it works for me
sorry for the previous solution but its not optimal i find a way to make it work
so instead of defaultvalues
you have to make its as value props
and if you want to catch the deleted and added values to your default
this function will help you alot
onChange = (e) => {
if (e === null) {
e = [];
}
this.setState({
equipments: e,
});
let added = e.filter((elm) => !this.state.equipments.includes(elm));
if (added[0]) {
let data = this.state.deletedEquipments.filter(
(elm) => elm !== added[0].label
);
this.setState({
deletedEquipments: data,
});
}
let Equipments = e.map((elm) => elm.label);
let newEquipments = Equipments.filter(
(elm) => !this.state.fixed.includes(elm)
);
this.setState({
newEquipments: newEquipments,
});
let difference = this.state.equipments.filter((elm) => !e.includes(elm));
if (difference.length !== 0) {
if (
!this.state.deletedEquipments.includes(difference[0].label) &&
this.state.fixed.includes(difference[0].label)
) {
this.setState({
deletedEquipments: [
...this.state.deletedEquipments,
difference[0].label,
],
});
}
}
};
constructor(props) {
super(props);
this.state = {
equipments: [],
newEquipments: [],
deletedEquipments: [],
};
}

Can variable be passing by function (react js)?

I wrote a class component and mutilple functions in it(class) , but don't know how variable be passing between different function.
class App extends Component {
state = {
stringA:null,
stringB:null
};
set_A = (event) =>{
const stringA = 'text';
}
copy_A = (event) =>{
const stringB = stringA;
}
render() {
return (
<>
<button onClick={this.set_A} type="click">set</button>
<button onClick={this.copy_A} type="click">copy</button>
</>
);}
}
export default App;
I reference this docs , but it only said function component without class component.
https://www.robinwieruch.de/react-function-component
or, are state and props not a kind of variable?
You access your properties with this.props and your state with this.state. You change state by calling setState which accepts partial states and merges them into the full state. It also triggers a re-render so that state changes can be seen in the UI.
class App extends Component {
state = {
stringA:null,
stringB:null
};
set_A = (event) => {
this.setState({ stringA: 'text' });
}
copy_A = (event) => {
this.setState({ stringB: this.state.stringA });
}
render() {
return (
<>
<button onClick={this.set_A} type="click">set</button>
<button onClick={this.copy_A} type="click">copy</button>
</>
);
}
}
export default App;
So in React, you would not be assigning a value to a variable like that. You would be utilizing State functionality. For Class-based React you would be using this.setState({stringA: 'text'})
or
this.setState({stringB: stringA})
Once the values are in the state you can access them anywhere in the component from the state object this.state.stringB for instance would have the value that was set once you had clicked on copy button
Example
set_A = (event) => {
this.setState({ stringA: 'text' });
console.log(this.state.stringB)
}
copy_A = (event) => {
this.setState({ stringB: this.state.stringA });
}
React Documentation is also a great resource to reference for Class and Function based component behaviors. https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class
You change state by calling setState in class based components
Try this :
class App extends Component {
state = { stringA:null, stringB:null };
set_A = (e) => {
this.setState({...state, stringA: 'text' });
}
copy_A = (e) => {
this.setState({ ...state,stringB: this.state.stringA });
}
render() {
return (
<>
<button onClick={this.set_A} type="click">set</button>
<button onClick={this.copy_A} type="click">copy</button>
</>
);
}
}
export default App;
Use the spread operator {...state} to change only the targeted piece of state you want to change with no change in the other pieces of the state.

Don't use constructor

In my code, I did not use constructor (). I've always seen people use the constructor in class components, but even though I'm not using it in that code, it's working perfectly. In my code, putting the state outside the constructor, is it a good idea or would it be better to use the constructor with the state set inside it? Can it give some sort of error in the future, or worsen my system's performance doing so? What is more advisable to do in this case?
import React, { Component, Fragment } from 'react'
import {Redirect} from 'react-router-dom'
import { connect } from 'react-redux'
import ActionCreator from '../redux/actionCreators'
import Button from '../elements/Button'
const statsgenre = {
'Ação': 'Action',
'Comédia': 'Comedy',
'Drama': 'Drama'
}
const statsuser = {
'Assistido' : 'Watched',
'Assistindo': 'Watching',
'Assistir': 'Watch'
}
class ScreensEditSeries extends Component{
state = {
id: '',
name: '',
status: '',
genre: '',
notes: ''
}
componentDidMount = () => {
const serie = {...this.props.match.params}
this.props.load(serie)
this.props.reset()
}
static getDerivedStateFromProps(newProps, prevState){
let serie = {}
if (prevState.name === '' || prevState.name === undefined){
if (newProps.series.serie.name !== prevState.name){
serie.name = newProps.series.serie.name
}
if (newProps.series.serie.genre !== prevState.genre){
serie.genre = newProps.series.serie.genre
}
if (newProps.series.serie.status !== prevState.status){
serie.status = newProps.series.serie.status
}
if (newProps.series.serie.notes !== prevState.notes){
serie.notes = newProps.series.serie.notes
}
return serie
}
}
saveSeries = () => {
const {name, status, genre, notes} = this.state
const id = this.props.match.params.id
const newSerie = {
id,
name,
status,
genre,
notes
}
this.props.save(newSerie)
}
handleChange = field => event => {
this.setState({[field] : event.target.value})
}
render(){
return (
<Fragment>
<div className="container">
<div>
{this.props.series.saved && <Redirect to={`/series/${this.props.match.params.genre}`}/>}
<h1 className='text-white'>Edit Série</h1>
{!this.props.series.isLoadding && <Button>
Name: <input type="text" value={this.state.name} onChange={this.handleChange('name')} className="form-control" /><br />
Status: {<span> </span>}
<select value={this.state.status} onChange={this.handleChange('status')}>
{Object.keys(statsuser)
.map( key => <option key={key}>{statsuser[key]}</option>)}
</select><br/><br/>
Genre: {<span> </span>}
<select value={this.state.genre} onChange={this.handleChange('genre')}>
{Object.keys(statsgenre)
.map(key => <option key={key}>{statsgenre[key]}</option>)}
</select><br/><br/>
Notes: <textarea type='text' value={this.state.notes} onChange={this.handleChange('notes')} className="form-control"></textarea><br />
<button className="button button2" type="button" onClick={this.saveSeries}>Save</button>
</Button>}
{this.props.series.isLoadding && <p className='text-info'>Loading...</p>}
</div>
</div>
</Fragment>
)
}
}
const mapStateToProps = state => {
return {
series: state.series
}
}
const mapDispatchToProps = dispatch => {
return {
load : serie => dispatch(ActionCreator.getSerieRequest(serie)),
save: newSerie => dispatch(ActionCreator.updateSerieRequest(newSerie)),
reset : () => dispatch(ActionCreator.seriesReset()),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ScreensEditSeries)
In general, you should only use a constructor if you need logic when the class is first created, or if your setup depends on the props passed in. Since everything in your initial state is hardcoded not using a constructor is fine in this case.
There is no problem in using class components without a constructor. Usually you need it in case you have to do some work to prepare the state, process some props or other setup some instance variables as soon as the component is instantiated.
It's ok :)
Here, instead, there is a very interesting post from Dan Abramov about why, if you need to use the constructor, is needed to call super(props):
https://overreacted.io/why-do-we-write-super-props/
Not super related to the question, but asking about constructor, I thought it could be useful to you.
There's no difference. The reason you see most people doing it inside of the constructor is because doing state = {} directly on the class is new syntax that hasn't been widely adopted yet (it often still requires a Babel or similar transformation). See proposal-class-fields for more information on it. One thing to note is that if you need to access any props to initialize the state, you have to do that in the constructor.

Notify react components about value change

Suppose that I have a component class which is responsible to change any number entered into textbox to text:
class NumbersToText extends Component {
onChange(event) {
const { target } = event;
const { value } = target;
if (hasNumbers(value)) {
target.value = numbersToText(value);
// HERE I NEED TO NOTIFY ABOUT CHANGES
}
}
render() {
return (
<span onChange={this.onChange}>
{this.props.children}
</span>
);
}
}
Now the usage would look something like this:
<NumbersToText>
<input onChange={this.saveValue}
</NumbersToText>
Let's say that all works, and the value gets changed to text.
Now the problem is that after I change numbers to text and assign that value to input onChange handlers are not executed again, thus saveValue is not called with updated value.
How should this problem be approached in order to trigger onChange handlers with new value?
I don't know exactly what you mean by numbers to text so I'll just assume you want to modify the value before calling the onChange function in the input, and also reflect that value in the input.
First of all, what you're doing will never work on React, React reflects internal virtual objects into the DOM, meaning you shloud not modify the DOM directly and instead you should modify this internal representantion (via setState, props) to reflect this change into the DOM.
There's also two types of inputs on React, controlled and uncontrolled. I will assume you want to use this on uncontrolled inputs.
The only possible solution I can see, is to transform the input using the React.cloneElement function adding a aditional step before calling the input's onChange callback.
Here's a possible implementation that will make the input uppercase.
class UpperCase extends React.Component {
constructor(props) {
super(props);
}
onChange(e, input, next) {
let value = input.value || '';
value = value.toUpperCase();
input.value = value;
next(value);
}
render() {
let childs = React.Children.map(this.props.children, child => {
let input = null; //Will take advantage of javascript's closures
let onChangeChild = child.props.onChange.bind(child);
return React.cloneElement(child, {
ref: ref => input = ref,
onChange: e => {
this.onChange(e, input, onChangeChild)
}
});
});
return (
<span>
{childs}
</span>
);
}
}
And you can use it like this:
<UpperCase>
<input onChange={(val) => console.log(val)}></input>
<textarea onChange={(val) => console.log(val)}></textarea>
</UpperCase>
Thanks to #tiagohngl I came up with a similar, but maybe a little less cluttered (without cloning elements) way:
class NumbersToText extends Component {
onChange(event) {
const { target } = event;
const { value } = target;
if (hasNumbers(value)) {
target.value = numbersToText(value);
this.childrenOnChange(event);
}
}
childrenOnChange(event) {
const { children } = this.props;
React.Children.forEach(children, child => {
if (child.props.onChange) {
child.props.onChange(event);
}
});
}
render() {
return (
<span onChange={this.onChange}>
{this.props.children}
</span>
);
}
}
export default class NumbersToText extends React.Component {
constructor(props) {
super(props)
this.onChange = this.onChange.bind(this);
}
componentWillMount() {
this.setState({ anyData: [] });
}
onChange(event) {
this.setState({anyData: event.target.value},
()=>{console.log("AnyData: "+this.state.anyData)});
// callback to console.log after setState is done
}
render() {
return (
<input type="text"
value={this.state.anyData}
onChange={this.onChange} />
);
}
}
As you mention that,
onChange is not called after changed value.
There are multiple possibilities.
onChange is not binded.
There are no state change in render method, so it will not re-render
make use of console.log() to trace the problem
I slightly ammend the code for illustration.
Hope it helps.
How react handle State Change (answer I posted before)

Categories

Resources