Search code examples
javascriptreactjsundefined

usestate variable shows undefined value?


I'm getting an undefined error on value variable which is a state. when logging the value in the console, It initially takes the value from props.value inside the useEffect. But then in concurrent renders it's written undefined so I'm guessing value variable becomes undefined after that. But this issue is not there when removing the value.length code. then the undefined error doesn't happen and the props.value is inside the textarea. But I need the value.length code to determine some CSS classes. Hence I'm guessing before the value variable is set by props.value, value.length code runs. But then the state default is set as "" so value.length` should return 0 even if it runs first right? So I'm not understanding why my state variable value is becoming undefined in between.

import React, { useState, useEffect } from "react";

const TextArea = (props) => {
  const [value, setValue] = useState("");

  useEffect(() => {
    window.sessionStorage.setItem(props.name, value);
  }, [value, props]);

  useEffect(() => {
    setValue(props.value);
  }, [props.value]);

  return (
    <div className="input-box input-box--3">
      <textarea
        required
        name={props.name}
        type="text"
        rows={props.rows}
        value={value}
        onChange={(event) => setValue(event.target.value)}
        className={
          console.log(value)
          // value.length === 0
          //   ? "input-box--field input-box--field--3"
          //   : "input-box--field input-box--field--3 input-box--field--3--not-empty"
        }
        autoComplete={props.autoComplete}
      />
      <span
        className={
          value.length === 0
            ? "input-box--placeholder"
            : "input-box--placeholder input-box--placeholder--not-empty"
        }
      >
        {props.placeholder}
      </span>
    </div>
  );
};

export default TextArea;

Solution

  • The value depends on the value prop, so if you'll pass something in this prop, it should work:

    https://codesandbox.io/s/mystifying-cartwright-x6ldj0?file=/src/App.js

    However, you can make it more bulletproof by checking if the passed prop is undefined:

      setValue(props.value ? props.value : "");