Value Template to keep previous sensor value when unknown

I have these Govee branded WiFi sensors that show temperature and humidity. Sadly the Govee API is pretty rubbish and it fails a lot which is causing my HA to show the sensors as either Unavailable or Unknown.

Looking for a bit of help configuring the value_template so it uses the previous “good” value rather than making the sensor come up as Unknown.

Existing code to pull from the API and format the data is:

  - resource: https://openapi.api.govee.com/router/api/v1/device/state
    method: POST
    headers:
        Content-Type: "application/json"
        Govee-API-Key: "XXXXXXXXXXXXX"
    payload: '{"requestId": "uuid", "payload": {"sku": "H5179", "device": "XXXXXXXX"}}' 
    scan_interval: 30
    sensor:
      - name: "Garage Freezer Humidity"
        value_template: "{{ value_json.payload.capabilities | selectattr('instance', 'equalto', 'sensorHumidity') | map(attribute='state.value.currentHumidity') | first }}"
        device_class: humidity
        unique_id: garage_freezer_govee_humidity
        unit_of_measurement: "% RH"
      - name: "Garage Freezer Temperature"
        value_template: "{{ (((value_json.payload.capabilities | selectattr('instance', 'equalto', 'sensorTemperature') | map(attribute='state.value') | first) - 32) * 5 / 9) | round(2) }}"
        device_class: temperature
        unit_of_measurement: "°C"
        unique_id: garage_freezer_govee_temperature

TIA.

      - name: "Garage Freezer Humidity"
        value_template: >- 
                {% set val =  value_json.payload.capabilities | selectattr('instance', 'equalto', 'sensorHumidity') | map(attribute='state.value.currentHumidity') | first %}
                {%- if val ==  "" -%}
                    {{ states('sensor.garage_freezer_humidity') }}
                {%- else -%}
                    {{ val }}
                {%- endif -%}
        device_class: humidity
        unique_id: garage_freezer_govee_humidity
        unit_of_measurement: "% RH"

I’m assuming the val becomes empty if the API fails. Else you need to change that part.