REACT: Stale state in functions but not markup

Viewed 54

I have a useEffect like this in my React Component:

useEffect(() => {
    async function init() {
      const result = await getCountries();
      const segmentRes = await getSegments();
      setCountries(result);
      setSegments(segmentRes);
      setShowSegments(segmentRes.length > 0);
      setDisableTeacherSignup(!(await doesTeacherCodeExist(teacherCode)));
    }
    init();
  }, [teacherCode]);

teacherCode is set like this when the page first renders: const teacherCode = paramQuery.get('code');

setSegments updates the state variable segments. The function is being executed correctly and the updated segments variable is reflected in the markup here (this is how I know the state is being updated when I would like it to):

<select id="teachingSpace" ref={segmentSelect} name="segmentId" onChange={toggleSchoolBoardVisibility} required>
    <option value="" disabled selected hidden>Choose...</option>
       { segments.map((x) => (
          <option value={x.segmentId}>{x.name}</option>
      )) }
</select>

However in the functions that use this segments variable and are called after the useEffect, segments is still the default value (unpopulated). The following is an example of a function that should use the updated segments variable, but uses the default instead.

const toggleSchoolBoardVisibility = () => {
    console.log(segments)
    if (segmentSelect.current.value === 'DEV') { // To Do: Remove hardcoded val
      setShowSchoolBoardInput(false);
    } else {
      setShowSchoolBoardInput(true);
    }
  };

EDIT: This is how the variables being used are defined:

export default function SignupTeacher() {
  const teacherCode = paramQuery.get('code');
  const [segments, setSegments] = useState([]);
....

EDIT: The file contains around 30 state variables. Could that be a reason that stale vars are being used?

0 Answers
Related