This is what I'm trying to do, inside the export default function
const Create = () => {
handleClose();
let temp = '';
if (thing1) {
temp= 'text';
}
if (thing2) {
temp = 'text';
}
if (thing3) {
temp = 'text';
}
if (thing4) {
temp = 'text';
}
if (thing5) {
temp = 'text';
}
setsel(temp);
Obviously I have something else for temp, having it loop through things to get a value but that's the basic idea - It comes back as undefined when I console.log "thing" to test it out.
CodePudding user response:
Utilising the answer from stackoverflow.com/a/67681192/10004072 to suit your context
import React, { useState, useEffect } from "react"
const [thing, setthing] = useState(''); // the state on update of which we want to call some function
const someAction = () => {
let temp = 'test';
setthing(temp); // the state will now be 'test'
}
useEffect(() => { // this hook will get called every time when thing has changed
console.log('Updated State', thing)
}, [thing])
CodePudding user response:
Your question is incomplete and lacks information. What exactly do you want to do?
If you want to set a value to the initial thing state, put inside the use state what you want to put. Example:
const [thing, setthing] = useState(test);
why do you want to set the value of another variable to the thing state? why not set it directly?
CodePudding user response:
Leslie's answer looks correct to me
Here is what's going wrong with example you shared:
Referring to the documentation: https://reactjs.org/docs/hooks-reference.html#usestate
The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.
setthing(temp)
is not going to change value of thing
in this render, it is going to render with current value, and then re-render the component with thing
set to temp
. Which in the sample example you shared will result in infinite renders.