# AUR0203

## Error Message

`AUR0203: Trying to retrieve a property or build a scope from a null/undefined scope`

## Description

This error occurs when Aurelia attempts to access properties or create a binding scope from a null or undefined scope context. This typically happens when there are issues with the component initialization, data binding context, or when trying to access properties before the binding context has been properly established.

## Common Scenarios

### Component Initialization Issues

```typescript
// ❌ Problem: Component not properly initialized
export class MyComponent {
  user: User; // undefined initially
  
  attached() {
    // If templates try to access user.name before user is set
    // this can cause scope issues
  }
}
```

### Template Binding Context Problems

```html
<!-- ❌ Problem: Accessing properties on undefined objects -->
<template>
  <div repeat.for="item of items">
    <!-- If items is undefined, this creates scope issues -->
    <span>${item.name}</span>
  </div>
</template>
```

### Lifecycle Timing Issues

```typescript
export class MyComponent {
  data: any[];
  
  constructor() {
    // ❌ Problem: Accessing binding context too early
    this.processData(); // Called before binding context is ready
  }
  
  processData() {
    // Tries to work with data that may not be bound yet
  }
}
```

## Solutions

### 1. **Initialize Properties Properly**

```typescript
export class MyComponent {
  // ✅ Correct: Initialize with default values
  user: User = { name: '', email: '' };
  items: Item[] = [];
  
  // ✅ Correct: Use proper lifecycle hooks
  binding() {
    // Initialize data when binding context is available
    this.loadUserData();
  }
  
  async loadUserData() {
    this.user = await this.userService.getCurrentUser();
  }
}
```

### 2. **Use Safe Navigation and Guards**

```html
<!-- ✅ Correct: Safe navigation -->
<template>
  <div if.bind="user">
    <span>${user.name}</span>
    <span>${user.email}</span>
  </div>
  
  <!-- ✅ Correct: Default values -->
  <span>${user?.name ?? 'Unknown'}</span>
  
  <!-- ✅ Correct: Conditional rendering -->
  <div repeat.for="item of items || []">
    <span>${item.name}</span>
  </div>
</template>
```

### 3. **Proper Lifecycle Management**

```typescript
export class MyComponent {
  user: User | null = null;
  loading = true;
  
  async binding() {
    // ✅ Correct: Load data during binding phase
    try {
      this.user = await this.userService.getCurrentUser();
    } finally {
      this.loading = false;
    }
  }
  
  unbinding() {
    // ✅ Correct: Clean up when unbinding
    this.user = null;
  }
}
```

### 4. **Handle Async Data Loading**

```html
<!-- ✅ Correct: Handle loading states using switch -->
<template switch.bind="true">
  <div case.bind="loading">Loading...</div>
  <div case.bind="user">
    <h2>${user.name}</h2>
    <p>${user.email}</p>
  </div>
  <div default-case>No user data available</div>
</template>
```

## Example: Complete Solution

```typescript
// user-profile.ts
import { bindable } from '@aurelia/runtime-html';

export class UserProfile {
  @bindable userId: string;
  
  user: User | null = null;
  loading = false;
  error: string | null = null;
  
  constructor(private userService: UserService) {}
  
  async binding() {
    if (this.userId) {
      await this.loadUser();
    }
  }
  
  userIdChanged() {
    // Called when userId bindable changes
    if (this.userId) {
      this.loadUser();
    } else {
      this.user = null;
    }
  }
  
  private async loadUser() {
    this.loading = true;
    this.error = null;
    
    try {
      this.user = await this.userService.getUser(this.userId);
    } catch (err) {
      this.error = 'Failed to load user';
      this.user = null;
    } finally {
      this.loading = false;
    }
  }
}
```

```html
<!-- user-profile.html -->
<template>
  <div class="user-profile" switch.bind="true">
    <div case.bind="loading" class="loading">
      Loading user profile...
    </div>

    <div case.bind="error" class="error">
      ${error}
    </div>

    <div case.bind="user" class="user-content">
      <h2>${user.name}</h2>
      <p>${user.email}</p>
      <div if.bind="user.address">
        <strong>Address:</strong>
        <p>${user.address.street}, ${user.address.city}</p>
      </div>
    </div>

    <div default-case class="no-user">
      No user selected
    </div>
  </div>
</template>
```

## Debugging Tips

1. **Check Initialization**: Ensure all properties used in templates are initialized
2. **Use Lifecycle Hooks**: Load data in appropriate lifecycle hooks (`binding`, `bound`)
3. **Add Guards**: Use conditional rendering and safe navigation operators
4. **Debug Context**: Use browser dev tools to inspect the binding context
5. **Check Timing**: Ensure data loading happens after the component is properly bound

## Related Errors

* [AUR0204](/developer-guides/error-messages/0203-to-0227/aur0204.md) - Create scope with null context
* [AUR0224](/developer-guides/error-messages/0203-to-0227/aur0224.md) - Invalid observable decorator usage


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.aurelia.io/developer-guides/error-messages/0203-to-0227/aur0203.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
