I've tried to ask this ungooglable to me question dozens of times. I've made almost the simpliest example possible to ask this question now.
I change the value of the hook in the handleChange method. But then console.log always shows previous value, not new one. Why is that?
I need to change the value of the hook and then instead of doing console.log use it to do something else. But I can't because the hook always has not what I just tried to put into it.
const options = ["Option 1", "Option 2"];
export default function ControllableStates() {
const [value, setValue] = React.useState(options[0]);
const handleChange = val => {
setValue(val);
console.log(value);
};
return (
<div>
<div>{value}</div>
<br />
<Autocomplete
value={value}
onChange={(event, newValue) => {
handleChange(newValue);
}}
options={options}
renderInput={params => (
<TextField {...params} label="Controllable" variant="outlined" />
)}
/>
</div>
);
}
You can try it here.
https://codesandbox.io/s/awesome-lumiere-y2dww?file=/src/App.js
I believe the problem is that you are logging the value in the handleChange function. Console logging the value outside of the function logs the correct value. Link: https://codesandbox.io/s/async-fast-6y71b
Hooks do not instantly update the value you want to update, as you might have expected with classes (though that wasn't guaranteed either)
State hook, when calling setValue will trigger a re-render. In that new render, the state will have the new value as you expected. That's why your console.log sees the old value.
Think of it as in each render, the state values are just local variables of that component function call. And think as the result of your render as a result of your state + props in that render call. Whenever any of those two changes (the props from your parent component; the state, from your setXXX function), a new render is triggered.
If you move out the console.log outside of the callback handler (that is, in the body of your rendered), there you will see in the render that happens after your interaction that the state is logged correctly.
In that sense, in your callbacks events from interactions, you just should worry about updating your state properly, and the next render will take care to, given the new props/state, re-render the result
The value doesn't "change" synchronously - it's even declared with a const, so even the concept of it changing inside the same scope doesn't make sense.
When changing state with hooks, the new value is seen when the component is rerendered. So, to log and do stuff with the "new value", examine it in the main body of the function:
const ControllableStates = () => {
const [value, setValue] = React.useState(options[0]);
const handleChange = val => {
setValue(val);
};
// ADD LOG HERE:
console.log('New or updated value:', value);
return (
<div>
<div>{value}</div>
<br />
<Autocomplete
value={value}
onChange={(event, newValue) => {
handleChange(newValue);
}}
options={options}
renderInput={params => (
<TextField {...params} label="Controllable" variant="outlined" />
)}
/>
</div>
);
}
You're printing out the old value in handleChange, not the new val.
i.e.
const handleChange = val => {
setValue(val);
console.log(value);
};
Should be:
const handleChange = val => {
setValue(val);
console.log(val);
};
Actually, lets get a little back and see the logic behind this scenario.
You should use the "handleChange" function ONLY to update the state hook, and let something else do the logic depends on that state hook value, which is mostly accomplished using "useEffect" hook.
You could refactor your code to look like this:
const handleChange = val => {
setValue(val);
};
React.useEffect(() => {
console.log(value);
// do your logic here
}, [value])
So I think that the main problem is that you're not understanding how React
deals with components and states.
So, I'll vastly simplify what React does.
React renders a new component and remembers it's state, it's inputs (aka
props) and it's the state and inputs of the children.
If at any given point an input changes or a state changes, React will render
the component again by calling the component function.
Consider this:
function SomeComponent(text) {
return (<div>The <i>text</i> prop has the value {text}</div>)
}
Let's say the initial prop value is "abc", React will call SomeComponent("abc"), then the function returns
<div>The <i>text</i> prop has the value abc</div> and React will render that.
If the prop text does not change, then React does nothing anymore.
Now the parent component changes the prop to "def", now React will call
SomeComponent("def") and it will return
<div>The <i>text</i> prop has the value def</div>, this is different from
last call, so React will update the DOM to reflect the change.
Now let's introduce state
function SomeComponent() {
const [name, setName] = React.useState("John")
function doSomething()
{
alert("The name is " + name)
}
return (
<p>Current name: {name}</p>
<button onClick={() => setName("Mary")}>Set name to Mary</button>
<button onClick={() => setName("James")}>Set name to James</button>
<button onClick={() => doSomething()}>Show current name</button>
)
}
So here React will call SomeComponent() and render the name John and the 3
button. Note that the value of the name variable does not change during the
current execution, because it's declared as const. This variable only reflects
the latest value of the state.
When you press the first button, setName() is executed. React will internally store
the new value for the state and because of the change of state, it will render
the component again, so SomeComponent() will be called once again. Now the variable name will
reflect again the latest value of the state (that's what useStatedoes), so in this case Mary. React
will realize that the DOM has to be updated and it prints the name Mary.
If you press the third button, it will call doSomething() which will print the
latest value of the name variable because every time React calls
SomeComponent(), the doSomething() function is created again with the latest
value of name. So once you've called setName(), you don't need to do
anything special to get the new value. React will take care of calling the
component function again.
So when you don't use class components but function components, you have to think
differently: the function gets called all the time by React and at any single
execution it reflects the latest state at that particular point in time. So when you
call the setter of a useState hook, you know that the component function will
be called again and useState will return the new value.
I recommend that you read this article, also read again Components and
Props from the React documentation.
So how should you do proceed? Well, like this:
const options = ["Option 1", "Option 2"];
export default function ControllableStates() {
const [value, setValue] = React.useState(options[0]);
const handleChange = val => {
setValue(val);
console.log(value);
};
const handleClick = () => {
// DOING SOMETHING WITH value
alter(`Now I'm going to do send ${value}`);
}
return (
<div>
<div>{value}</div>
<br />
<Autocomplete
value={value}
onChange={(event, newValue) => {
handleChange(newValue);
}}
options={options}
renderInput={params => (
<TextField {...params} label="Controllable" variant="outlined" />
)}
/>
<button type="button" onClick={handleClick}>Send selected option</button>
</div>
);
}
See CodeSandbox.
Related
I have a data array that I am mapping onto a material-ui Typography.
{
array.map((item, id)=> <Typography key={id} value={item.name} />)
}
The code displays the typography with their respective values on the browser as expected, however, I am trying to set the mapped value of Typography into a state like this...
const [data, setData] = useState();
...
{
array.map((item, id) =>
<Typography key={id} value={item.name} {(e)=>setData(e.target.value)} />
)}
This method does not work.
How do I make data to be the value of <Typography/>
If I understand correctly, you're trying to store item.name within local state? How are you receiving the data that you are mapping through?
Are you trying to store each item you're mapping through and represent key-value pairs of an object within local state? What are you trying to do with the state once you have it?
As far as I know, there's is no way to assign values to local state while you are mapping through an array. However, there are multiple ways to assign the data to local state outside of the return.
Also, what is this line doing?
{(e)=>setData(e.target.value)}
It seems you're trying to create a controlled input on a Typography component without an onChange prop, as well as on a component that does not take input.
One more aside, although it is not a big deal -
{
array.map((item, id) =>
<Typography key={id} value={item.name} ..../>
)}
id here is usually referred to as index
Edited for answer
I normally use Redux to manage the global state, but the process should be the same for Context Provider:
const yourComponent = () => {
const [data, setData] = useState();
// This is the array you get from the Context Provider
const yourArray = getArrayFromContextProvider();
useEffect(() => {
// If you want to normalize the array data
if (yourArray) {
const dataObj = {};
yourArray.forEach((item, index) => {
// Make the key unique by using the item id OR you can use index
dataObj[item.id] = item;
// OR you can add the item value as the key
dataObj[item.value] = item;
});
setData(dataObj);
}
// If you just want to store the array
if (yourArray) {
setData(yourArray)
}
}, [yourArray]);
return <div>
{/* ...Your map */}
</div>;
};
export default yourComponent
I have this FormControl element with Select that accepts an array of options that is being used for MenuItem options and also a value as props and this component looks like this:
const TaxonomySelector = (props) => {
const { isDisabled, taxonomies, selectedTaxonomy, handleTaxonomyChange } = props;
return (
<Grid item xs={12}>
{console.log(selectedTaxonomy)}
{console.log(taxonomies)}
<FormControl disabled={isDisabled} fullWidth>
<InputLabel>Таксономия</InputLabel>
<Select
value={selectedTaxonomy || ''}
onChange={handleTaxonomyChange}>
{Object.values(taxonomies).map((taxonomy) => (
<MenuItem key={taxonomy.id} name={taxonomy.name} value={taxonomy}>
{taxonomy.name} от {moment(taxonomy.date).format('YYYY-MM-DD')}
</MenuItem>
))}
</Select>
</FormControl>
</Grid>
);
};
The values that I pass as props are correctly displaying as filled out in the console at all stages the component is being rendered. And also in the case when this component is used for selection through using handleTaxonomyChange function everything is working correctly with user being able to select a particular option out of the array provided to the MenuItem. However, the problem occurs in case when the parent component of this component is being open for View Only or with already pre-defined values. In this case I get the following:
It seems like there's something is being passed to the Select component (even I checked through React Component in DevTools and value was showed correctly) but for some reason it is not being displayed.
The parent component contains the following code related to this part:
const INITIAL_SELECTED_TAXONOMY = null;
const [selectedTaxonomy, setSelectedTaxonomy] = useState(INITIAL_SELECTED_TAXONOMY);
const handleTaxonomyChange = (e) => setSelectedTaxonomy(e.target.value);
useEffect(() => {
getTaxonomies();
}, []);
useEffect(() => {
if (viewTypeOnlyView) {
handleStageChange(1);
handleDialogTitleChange('Конструктор КС. Режим просмотра');
}
if (viewTypeEdit) {
handleDialogTitleChange('Конструктор КС. Режим редактирования');
}
if (viewTypeCopy) {
handleDialogTitleChange('Конструктор КС. Дублирование КС');
}
if (defaultData) {
if (defaultData.name) setName(defaultData.name);
if (defaultData.taxonomy) setSelectedTaxonomy(defaultData.taxonomy);
// if (defaultData.entryPoints) setSelectedEntryPoints(defaultData.entryPoints);
if (defaultData.entryPoints) {
getEntryPointDescsFn('4.1', defaultData.entryPoints);
}
if (defaultData.message) setMessage(defaultData.message);
}
}, [viewType]);
ViewType is a prop that is being passed to this component and calling those methods in order to fill up the state with predefined values.
And the TaxonomySelector component inside the return statement:
<TaxonomySelector
taxonomies={taxonomies}
isDisabled={currentStage === 1}
selectedTaxonomy={selectedTaxonomy}
handleTaxonomyChange={handleTaxonomyChange} />
At first I thought that the issue could be related to how the component is being rendered and maybe it renders before that data pre-fill useEffect hook is being triggered. However, it seems that other elements, like the ones with string values name and message are being correctly filled out with no issues. Seems like that the issue is specifically related to Select elements. Could you let me know what could it possibly be?
Looks like disabled prop in FormControl is true.
For debug set disabled prop false
I am new to react and material UI and struggling to load Autocomplete component options dynamically.
Initially, I am setting empty array as initial option until data is fetched from the database. Once I get my data I update the Autocomplete options with my data and it's working but at the same time I am getting the following warning
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
My code
const [listItems, setListItems] = useState([]);
const {formik, items} = props;
const handleGetOptionSelected = (option, value) => {
if (!items) {
return {};
}
return option.id === value.id;
};
const handleGetOptionLabel = (option) => {
if (!items) {
return 'No Options';
}
return option.name;
};
useEffect(() => {
if (items) {
setListItems(items);
}
}, [items]);
return (
<Autocomplete
className={classes.autoComplete}
multiple
id="tags-standard"
options={listItems}
getOptionLabel={(option) => handleGetOptionLabel(option)}
getOptionSelected={(option, value) => handleGetOptionSelected(option, value)}
onChange={(event, selectedValues) => {
formik.setFieldValue(
"tag_ids",
getCollectionColumn(selectedValues, 'id'),
false
);
}}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
placeholder="select tags"
name="tag_ids"
error={formik.touched.tag_ids && Boolean(formik.errors.tag_ids)}
helperText={formik.touched.tag_ids && formik.errors.tag_ids}
/>
)}
/>
);
For an input to be controlled, its value must correspond to that of a state variable.
That condition is not initially met in your example because your state is not initially set before onChange. Therefore, the input is initially uncontrolled. Once the onChange handler is triggered for the first time, your formik data state gets set. At that point, the above condition is satisfied and the input is considered to be controlled. This transition from uncontrolled to controlled produces the error seen above.
By initializing formik data structure in the constructor to an empty string
the input will be controlled from the start, fixing the issue.
e.g If you want to set name inside formik then initialize it as empty string then change it
on onChange according to need. Like this:
constructor(props) {
super(props);
this.state = { name: '' }
}
I don't know your data structure so you can try this on your own by mimicking this.
See React Controlled Components for more examples. Also try this solution
I'm building a component like:
class IncrementField extends Component {
inputRef;
changeValue() {
this.inputRef.value = parseInt(this.inputRef.value) + 1;
}
render() {
const { ...other } = this.props;
return (
<StyledField>
<StyledButton onClick={this.changeValue.bind(this)}>-</StyledButton>
<StyledTextField
{...other}
inputRef={input => (this.inputRef = input)}
type={'number'}
InputProps={{
readOnly: true,
}}
/>
<StyledButton onClick={this.changeValue.bind(this)}>+</StyledButton>
</StyledField>
)
}
}
It's purpose is to be used in a Formik form like
<IncrementField
name={`fieldname`}
key="fieldname"
value={values.fieldname}
onChange={changeAndSubmit.bind(this)}
autoComplete="false">
</IncrementField>
Its a component like
- 1 +
where you click on + and - and the value is incremented/decremented.
Sounds simple but I can't figure out how to change the value from the inside. StyledTextField is a #material-ui/core/TextField wrapped with styled-components.
What I want to do is to trigger the onChange event which is obviously passed in props and further placed with {...other}. I can change the value of the input, but it's probably not the way it should be done - because the onChange isnt triggered - and the Formik's form isnt changed.
I tried the approach I pasted, I tried also with having the value in state, but the onChange never fires... how to do that?
One way of doing that in Angular could be using an #Output() decorator, how does it look like in React?
The value should always be saved by Formik - so if a change happens, you should call Formiks handleChange in your changeValue function.
handleChange takes a React.ChangeEvent<HTMLInputElement>, so you have to create a fake event and call the handleChange function with it.
const evt = {target: {name: this.props.name, value: this.props.value + 1}}
this.props.handleChange(evt);
In a class based React component I do something like this:
class SomeComponent extends React.Component{
onChange(ev){
this.setState({text: ev.currentValue.text});
}
transformText(){
return this.state.text.toUpperCase();
}
render(){
return (
<input type="text" onChange={this.onChange} value={this.transformText()} />
);
}
}
This is a bit of a contrived example to simplify my point. What I essentially want to do is maintain a constant reference to the onChange function. In the above example, when React re-renders my component, it will not re-render the input if the input value has not changed.
Important things to note here:
this.onChange is a constant reference to the same function.
this.onChange needs to be able to access the state setter (in this case this.setState)
Now if I were to rewrite this component using hooks:
function onChange(setText, ev) {
setText(ev.currentValue.text);
};
function transformText(text) {
return text.toUpperCase();
};
function SomeComponent(props) {
const [text, setText] = useState('');
return (
<input type="text" onChange={onChange} value={transformText()} />
);
}
The problem now is that I need to pass text to transformText and setText to onChange methods respectively. The possible solutions I can think of are:
Define the functions inside the component function, and use closures to pass the value along.
Inside the component function, bind the value to the methods and then use the bound methods.
Doing either of these will change the constant reference to the functions that I need to maintain in order to not have the input component re-render. How do I do this with hooks? Is it even possible?
Please note that this is a very simplified, contrived example. My actual use case is pretty complex, and I absolutely don't want to re-render components unnecessarily.
Edit:
This is not a duplicate of What useCallback do in React? because I'm trying to figure out how to achieve a similar effect to what used to be done in the class component way, and while useCallback provides a way of doing it, it's not ideal for maintainability concerns.
This is where you can build your own hook (Dan Abramov urged not to use the term "Custom Hooks" as it makes creating your own hook harder/more advanced than it is, which is just copy/paste your logic) extracting the text transformation logic
Simply "cut" the commented out code below from Mohamed's answer.
function SomeComponent(props) {
// const [text, setText] = React.useState("");
// const onChange = ev => {
// setText(ev.target.value);
// };
// function transformText(text) {
// return text.toUpperCase();
// }
const { onChange, text } = useTransformedText();
return (
<input type="text" onChange={React.useCallback(onChange)} value={text} />
);
}
And paste it into a new function (prefix with "use*" by convention).
Name the state & callback to return (either as an object or an array depending on your situation)
function useTransformedText(textTransformer = text => text.toUpperCase()) {
const [text, setText] = React.useState("");
const onChange = ev => {
setText(ev.target.value);
};
return { onChange, text: textTransformer(text) };
}
As the transformation logic can be passed (but uses UpperCase by default), you can use the shared logic using your own hook.
function UpperCaseInput(props) {
const { onChange, text } = useTransformedText();
return (
<input type="text" onChange={React.useCallback(onChange)} value={text} />
);
}
function LowerCaseInput(props) {
const { onChange, text } = useTransformedText(text => text.toLowerCase());
return (
<input type="text" onChange={React.useCallback(onChange)} value={text} />
);
}
You can use above components like following.
function App() {
return (
<div className="App">
To Upper case: <UpperCaseInput />
<br />
To Lower case: <LowerCaseInput />
</div>
);
}
Result would look like this.
You can run the working code here.
Define the callbacks inside the component function, and use closures to pass the value along. Then what you are looking for is useCallback hook to avoid unnecessary re-renders. (for this example, it's not very useful)
function transformText(text) {
return text.toUpperCase();
};
function SomeComponent(props) {
const [text, setText] = useState('');
const onChange = useCallback((ev) => {
setText(ev.target.value);
}, []);
return (
<input type="text" onChange={onChange} value={transformText(text)} />
);
}
Read more here
I know it's bad form to answer my own question but based on this reply, and this reply, it looks like I'll have to build my own custom hook to do this.
I've basically built a hook which binds a callback function with the given arguments and memoizes it. It only rebinds the callback if the given arguments change.
If anybody would find a need for a similar hook, I've open sourced it as a separate project. It's available on Github and NPM.
The case isn't specific to hooks, it would be the same for class component and setState in case transformText and onChange should be extracted from a class. There's no need for one-line functions to be extracted, so it can be assumed that real functions are complex enough to justify the extraction.
It's perfectly fine to have transform function that accepts a value as an argument.
As for event handler, it should have a reference to setState, this limits ways in which it can be used.
A common recipe is to use state updater function. In case it needs to accept additional value (e.g. event value), it should be higher-order function.
const transformText = text => text.toUpperCase();
const onChange = val => _prevState => ({ text: val });
function SomeComponent(props) {
const [text, setText] = useState('');
return (
<input type="text" onChange={e => setText(onChange(e.currentValue.text)} value={transformText(text)} />
);
}
This recipe doesn't look useful in this case because original onChange doesn't do much. This also means that the extraction wasn't justified.
A way that is specific to hooks is that setText can be passed as a callback, in contrast to this.setState. So onChange can be higher-order function:
const transformText = text => text.toUpperCase();
const onChange = setState => e => setState({ text: e.currentValue.text });
function SomeComponent(props) {
const [text, setText] = useState('');
return (
<input type="text" onChange={onChange(setText)} value={transformText(text)} />
);
}
If the intention is to reduce re-renders of children caused by changes in onChange prop, onChange should be memoized with useCallback or useMemo. This is possible since useState setter function doesn't change between component updates:
...
function SomeComponent(props) {
const [text, setText] = useState('');
const memoizedOnChange = useMemo(() => onChange(setText), []);
return (
<input type="text" onChange={memoizedOnChange} value={transformText(text)} />
);
}
The same thing can be achieved by not extracting onChange and using useCallback:
...
function SomeComponent(props) {
const [text, setText] = useState('');
const onChange = e => setText({ text: e.currentValue.text });
const memoizedOnChange = useCallback(onChange, []);
return (
<input type="text" onChange={memoizedOnChange} value={transformText(text)} />
);
}