1

I'm trying to track the text input value using states but "e.target.value" doesn't seem to work(maybe because my component is declared as a function). Is there any other way I can do it?

const UncontrolledDiagram = ({ sentence }) => {
  // create diagrams schema

  const [schema, { onChange, addNode, connect, removeNode }] = useSchema(initialSchema);

  const [selected, setSelected] = useState([]);

  const [textInput,setInput]=useState('')
  
  const handleTextChange=(e)=>{
    setInput(e.target.value);
    console.log(textInput);
  }

This is the input field I am tracking:

const conditionalDisplay=(id)=>{
    const nodeToCheck=schema.nodes.find(node=>node.id=== id);
    if(nodeToCheck.form===null){
      return(
        <div>
          <label>Form: </label><input style={{ width: '25px', height: '12px' }} onChange={handleTextChange} type='text'></input>
          <button className='buttonInputSubmit'>+</button>
        </div>
      )
    }
    else{
      return(
        <div style={{display: 'flex',margin: '0'}}>
          <label>Form: </label><p style={{color: 'yellow', marginLeft:'2px'}}>{nodeToCheck.form}</p>
        </div>
      )
    }
  }

1 Answer 1

1

It works, your console.log(textInput) still has the old state because state is set asynchronously. It will set the state as soon as your function has been fully executed.

const handleTextChange=(e)=>{
   setInput(e.target.value);
}

useEffect(() => {
    console.log(textInput);
}, [textInput])
Sign up to request clarification or add additional context in comments.

1 Comment

that's because you are console logging in a syncronous way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.