ERROR  TypeError: Cannot read property 'name' of undefined

This error is located at:
    in ProfileScreen (created by SceneView)

here are my files
// context/AuthContext.js

import React, { createContext, useState, useEffect } from 'react';
import * as SecureStore from 'expo-secure-store';

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
    const [authToken, setAuthToken] = useState(null);
    const [loading, setLoading] = useState(true);

    const SIGNIN_KEY = 'authToken';

    const signIn = async (token) => {
        setAuthToken(token);
        try {
            await SecureStore.setItemAsync(SIGNIN_KEY, token);
            console.log('Token stored successfully.');
        } catch (error) {
            console.error('Error storing the token:', error);
        }
    };

    const signOut = async () => {
        setAuthToken(null);
        try {
            await SecureStore.deleteItemAsync(SIGNIN_KEY);
            console.log('Token removed successfully.');
        } catch (error) {
            console.error('Error removing the token:', error);
        }
    };

    const loadToken = async () => {
        try {
            const token = await SecureStore.getItemAsync(SIGNIN_KEY);
            if (token) {
                setAuthToken(token);
                console.log('Token loaded from SecureStore:', token);
            } else {
                console.log('No token found.');
            }
        } catch (e) {
            console.log('Failed to load token:', e);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        loadToken();
    }, []);

    return (
        <AuthContext.Provider value={{ authToken, signIn, signOut }}>
            {!loading && children}
        </AuthContext.Provider>
    );
};

// screens/ProfileScreen.js

import React, { useContext } from 'react';
import { View, StyleSheet, ScrollView, Alert } from 'react-native';
import { Title, Caption, Text, Button } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { AuthContext } from '../context/AuthContext';
import { useTheme } from 'react-native-paper';

/**
 * Simple Profile Screen Component
 */
const ProfileScreen = ({ navigation }) => {
  const { user, logout } = useContext(AuthContext);
  const theme = useTheme(); // Access the current theme

  // Handler for logout action
  const handleLogout = () => {
    Alert.alert(
      'Logout',
      'Are you sure you want to logout?',
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Logout',
          style: 'destructive',
          onPress: () => logout(),
        },
      ],
      { cancelable: true }
    );
  };

  return (
    <ScrollView style={[styles.container, { backgroundColor: theme.colors.background }]}>
      {/* User Information Section */}
      <View style={styles.userInfoSection}>
        <Title style={[styles.title, { color: theme.colors.text }]}>{user.name}</Title>
        <Caption style={[styles.caption, { color: theme.colors.text }]}>{user.email}</Caption>
      </View>

      {/* Logout Button */}
      <View style={styles.logoutSection}>
        <Button
          mode="contained"
          icon="logout"
          onPress={handleLogout}
          style={styles.logoutButton}
          contentStyle={styles.buttonContent}
          accessibilityLabel="Logout"
          accessibilityHint="Logs you out of the application"
        >
          Logout
        </Button>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  userInfoSection: {
    paddingHorizontal: 20,
    paddingVertical: 40,
    alignItems: 'center', // Center the user info
    backgroundColor: 'transparent',
  },
  title: {
    fontSize: 26,
    fontWeight: 'bold',
  },
  caption: {
    fontSize: 16,
    lineHeight: 16,
    marginTop: 5,
  },
  logoutSection: {
    paddingHorizontal: 20,
    marginTop: 30,
    alignItems: 'center', // Center the logout button
  },
  logoutButton: {
    width: '100%', // Make the button stretch across the container
    borderRadius: 5,
    backgroundColor: undefined, // Let the theme handle the color
  },
  buttonContent: {
    height: 50, // Ensures consistent button height
    justifyContent: 'center',
  },
});

export default ProfileScreen;

backend
// controllers/authController.js

const jwt = require('jsonwebtoken');
const User = require('../models/User'); // Adjust the path as necessary

// Function to generate JWT
const generateToken = (userId) => {
    return jwt.sign(
        { userId },
        process.env.JWT_SECRET, // Ensure this matches the secret in auth.js
        { expiresIn: '1h' }      // Token validity duration
    );
};

// Login Function
const login = async (req, res) => {
    const { username, password } = req.body;

    try {
        // Find user by username
        const user = await User.findOne({ username });
        if (!user) {
            return res.status(400).json({ message: 'Invalid credentials' });
        }

        // Check if password matches
        const isMatch = await user.comparePassword(password); // Implement comparePassword in your User model
        if (!isMatch) {
            return res.status(400).json({ message: 'Invalid credentials' });
        }

        // Generate token
        const token = generateToken(user._id);

        // Return token to client
        res.json({ token });
    } catch (err) {
        console.error('Login error:', err);
        res.status(500).json({ message: 'Server error' });
    }
};

// Register Function (Optional)
const register = async (req, res) => {
    const { username, password } = req.body;

    try {
        // Check if user already exists
        let user = await User.findOne({ username });
        if (user) {
            return res.status(400).json({ message: 'User already exists' });
        }

        // Create new user
        user = new User({ username, password });
        await user.save();

        // Generate token
        const token = generateToken(user._id);

        // Return token to client
        res.json({ token });
    } catch (err) {
        console.error('Registration error:', err);
        res.status(500).json({ message: 'Server error' });
    }
};

module.exports = { login, register };
// middleware/auth.js
const jwt = require('jsonwebtoken');
require('dotenv').config(); // Ensure environment variables are loaded

/**
 * Authentication middleware to verify JWT tokens.
 */
const auth = (req, res, next) => {
    const authHeader = req.header('Authorization');

    if (!authHeader) {
        console.warn('No Authorization header provided.');
        return res.status(401).json({ message: 'No token, authorization denied' });
    }

    // The expected format is "Bearer <token>"
    const parts = authHeader.split(' ');
    if (parts.length !== 2 || parts[0] !== 'Bearer') {
        console.warn('Invalid Authorization header format.');
        return res.status(401).json({ message: 'Token is not valid' });
    }

    const token = parts[1];

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded.userId; // Ensure your JWT payload contains `userId`
        console.log('Token verified. User ID:', req.user);
        next();
    } catch (err) {
        console.error('Token verification failed:', err);
        res.status(401).json({ message: 'Token is not valid' });
    }
}

module.exports = auth;

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const UserSchema = new mongoose.Schema({
    username: { type: String, required: true, unique: true },
    email:    { type: String, required: true, unique: true },
    password: { type: String, required: true },
    role: { type: String, enum: ['user', 'admin'], default: 'user' }, // Added role field
    desiredPhysique: { type: String, enum: ['lean', 'muscular', 'athletic'], required: true },
    fitnessGoals: [String], // e.g., ['strength', 'endurance']
    dietaryPreferences: [String],
    dietaryRestrictions: [String],
}, { timestamps: true });

// Password hashing middleware
UserSchema.pre('save', async function(next) {
    if (!this.isModified('password')) return next();
    try {
        const salt = await bcrypt.genSalt(10);
        this.password = await bcrypt.hash(this.password, salt);
        next();
    } catch(err) {
        next(err);
    }
});

// Password comparison method
UserSchema.methods.comparePassword = function(candidatePassword) {
    return bcrypt.compare(candidatePassword, this.password);
}

module.exports = mongoose.model('User', UserSchema);

// routes/auth.js
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require('../models/User');

// Register Route
router.post('/register', async (req, res) => {
    const { username, email, password, desiredPhysique, fitnessGoals, dietaryPreferences, dietaryRestrictions } = req.body;
    try {
        const existingUser = await User.findOne({ email });
        if (existingUser) {
            return res.status(400).json({ message: 'Email already in use' });
        }

        const newUser = new User({
            username,
            email,
            password,
            desiredPhysique,
            fitnessGoals,
            dietaryPreferences,
            dietaryRestrictions,
        });
        await newUser.save();

        const payload = { userId: newUser._id };
        const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1h' });

        res.status(201).json({ token, message: 'User registered successfully' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

// Login Route
router.post('/login', async (req, res) => {
    const { email, password } = req.body; // Changed from username to email for consistency
    try {
        const user = await User.findOne({ email });
        if (!user) return res.status(400).json({ message: 'Invalid credentials' });

        const isMatch = await user.comparePassword(password);
        if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' });

        const payload = { userId: user._id };
        const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1h' });

        res.json({ token, message: 'Login successful' });
    } catch(err) {
        res.status(500).json({ error: err.message });
    }
});

module.exports = router;