Hall Effect Sensor with L298

I got L298 working with a Serial monitor for the train. I just add Hall Sensor at the end of the track. The loco has a small magnetic underneath by wheel. It is working when the loco goes over the hall sensor and it stops but I can't run the loco again to reverse unless I had to move it away from the hall sensor and hit 6 to reverse to run again. Here is my code for it. Can someone help me with this? Also, I would like to add two servos for turnout. I am not sure how to do this.

// Sensor
int SENSOR = 2 ; // define the Hall magnetic sensor

// Motor A connections
int enA = 9;
int in1 = 8;
int in2 = 7;

void setup() {
  pinMode (SENSOR, INPUT) ;  // define the Hall magnetic sensor line as input
   
  // Set all the motor control pins to outputs for L298
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  // Start up serial connection
  Serial.begin(9600);
  
  // Turn off motors - Initial state
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);

void loop()
{
  while (digitalRead(SENSOR) == LOW){
    Serial.println("Magnetic field detected");
    digitalWrite(in1, LOW);
    digitalWrite(in2, LOW);
  }
  if (Serial.available())
    {
    int state = Serial.parseInt();
    
    if (state == 0){
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      }
   if (state == 1){
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      analogWrite(enA, 120);
      }
    
   if (state == 6){
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      analogWrite(enA, 100);
      }
  }  
}

This is the classic homing-switch problem. You only want to prevent forward motion when the
magnet is detected, not all motion.

Thus you'll need to take into account the intended direction of motion before checking the
hall sensor. If forward, check the switch, if reverse, don't...

Look up "state change detection".

You have to switch off the loco when the hall sensor signal goes low (changes state), not when it is low as your code does. It will even get stuck in that while() loop until you remove the signal...