Skip to main content

Update Player Profile

The updateProfile() method allows you to modify player profile information after authentication. You can update the player's name, contact details, profile picture, and push notification settings.

Overview

Profile updates are sent to Moitribe servers and synchronized across all devices. Updates are processed asynchronously, with results returned through a callback function.

info

Players must be authenticated before updating their profile. Guest players cannot update profile information.

Basic Usage

JavaScript Example

MoitribeSDK('my-game-id', 'updateProfile', {
name: 'NewPlayerName',
callback: (result) => {
if (result.success) {
console.log('Profile updated successfully');
} else {
console.error('Update failed:', result.msg);
}
}
});

TypeScript Example

import MoitribeSDK from '@veniso/moitribe-js';

interface UpdateProfileParams {
name?: string;
emailid?: string;
phno?: string;
picture?: string;
gfcmid?: string;
callback?: (result: UpdateProfileResult) => void;
}

interface UpdateProfileResult {
success: boolean;
msg?: string;
statuscode?: number;
playerdata?: SignedInProfile;
}

MoitribeSDK('my-game-id', 'updateProfile', {
name: 'NewPlayerName',
callback: (result: UpdateProfileResult) => {
if (result.success) {
console.log('Profile updated successfully');
if (result.playerdata) {
console.log('Updated profile:', result.playerdata);
}
} else {
console.error('Update failed:', result.msg);
}
}
});

Parameters

ParameterTypeRequiredDescription
namestringNoPlayer's display name
emailidstringNoPlayer's email address
phnostringNoPlayer's phone number
picturestringNoURL to profile picture
gfcmidstringNoFirebase Cloud Messaging ID for push notifications
callbackfunctionYesCallback function to handle the response
tip

You can update multiple fields in a single call by including multiple parameters.

Response Format

The callback receives a result object with the following structure:

{
success: boolean; // true if update succeeded
msg?: string; // Error message if update failed
statuscode?: number; // HTTP status code
playerdata?: SignedInProfile; // Updated profile (may not always be present)
}

Common Use Cases

Update Player Name

Allow players to change their display name:

function changePlayerName(newName) {
// Validate name
if (!newName || newName.length < 3) {
alert('Name must be at least 3 characters long');
return;
}

if (newName.length > 20) {
alert('Name must be less than 20 characters');
return;
}

// Update profile
MoitribeSDK('my-game-id', 'updateProfile', {
name: newName,
callback: (result) => {
if (result.success) {
alert('Name updated successfully!');
// Update UI
document.getElementById('player-name').textContent = newName;
} else {
alert('Failed to update name: ' + result.msg);
}
}
});
}

Update Email Address

Update the player's email:

function updateEmail(newEmail) {
// Validate email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(newEmail)) {
alert('Please enter a valid email address');
return;
}

MoitribeSDK('my-game-id', 'updateProfile', {
emailid: newEmail,
callback: (result) => {
if (result.success) {
console.log('Email updated to:', newEmail);
alert('Email updated successfully!');
} else {
console.error('Email update failed:', result.msg);
alert('Failed to update email');
}
}
});
}

Update Phone Number

Update the player's phone number:

function updatePhoneNumber(newPhone) {
// Validate phone format (basic validation)
const phoneRegex = /^\+?[1-9]\d{9,14}$/;
if (!phoneRegex.test(newPhone)) {
alert('Please enter a valid phone number');
return;
}

MoitribeSDK('my-game-id', 'updateProfile', {
phno: newPhone,
callback: (result) => {
if (result.success) {
console.log('Phone updated successfully');
alert('Phone number updated!');
} else {
alert('Failed to update phone number: ' + result.msg);
}
}
});
}

Update Profile Picture

Update the player's profile image:

function updateProfilePicture(imageUrl) {
// Validate URL format
try {
new URL(imageUrl);
} catch (error) {
alert('Invalid image URL');
return;
}

MoitribeSDK('my-game-id', 'updateProfile', {
picture: imageUrl,
callback: (result) => {
if (result.success) {
console.log('Profile picture updated');
// Update UI immediately
document.getElementById('avatar').src = imageUrl;
alert('Profile picture updated!');
} else {
alert('Failed to update picture: ' + result.msg);
}
}
});
}

Update Multiple Fields

Update several profile fields at once:

function updateProfileForm(formData) {
const updates = {};

if (formData.name) {
updates.name = formData.name;
}

if (formData.email) {
updates.emailid = formData.email;
}

if (formData.phone) {
updates.phno = formData.phone;
}

if (formData.picture) {
updates.picture = formData.picture;
}

// Add callback
updates.callback = (result) => {
if (result.success) {
alert('Profile updated successfully!');
refreshProfileDisplay();
} else {
alert('Failed to update profile: ' + result.msg);
}
};

MoitribeSDK('my-game-id', 'updateProfile', updates);
}

Register for Push Notifications

Update Firebase Cloud Messaging ID for push notifications:

function registerPushNotifications() {
// Get FCM token (Firebase setup required)
firebase.messaging().getToken().then((fcmToken) => {
MoitribeSDK('my-game-id', 'updateProfile', {
gfcmid: fcmToken,
callback: (result) => {
if (result.success) {
console.log('Push notifications registered');
} else {
console.error('Failed to register push notifications');
}
}
});
}).catch((error) => {
console.error('Error getting FCM token:', error);
});
}

Error Handling

Handle different types of update errors:

MoitribeSDK('my-game-id', 'updateProfile', {
name: 'NewName',
emailid: 'newemail@example.com',
callback: (result) => {
if (result.success) {
console.log('Profile updated successfully');

// Update local cache if new profile data is returned
if (result.playerdata) {
currentPlayer = result.playerdata;
updateGameUI();
}
} else {
// Handle specific error codes
switch (result.statuscode) {
case 400:
alert('Invalid profile data. Please check your input.');
break;
case 401:
alert('You must be logged in to update your profile.');
showLoginScreen();
break;
case 409:
alert('This name or email is already taken.');
break;
case 429:
alert('Too many requests. Please try again later.');
break;
default:
alert('Failed to update profile: ' + (result.msg || 'Unknown error'));
}
}
}
});

Complete Profile Update Form

Here's a complete example with a form and validation:

// HTML form
/*
<form id="profile-form">
<input type="text" id="name-input" placeholder="Display Name">
<input type="email" id="email-input" placeholder="Email">
<input type="tel" id="phone-input" placeholder="Phone">
<button type="submit">Update Profile</button>
</form>
*/

document.getElementById('profile-form').addEventListener('submit', (e) => {
e.preventDefault();

const name = document.getElementById('name-input').value.trim();
const email = document.getElementById('email-input').value.trim();
const phone = document.getElementById('phone-input').value.trim();

// Validate inputs
const errors = [];

if (name && name.length < 3) {
errors.push('Name must be at least 3 characters');
}

if (email && !isValidEmail(email)) {
errors.push('Invalid email address');
}

if (phone && !isValidPhone(phone)) {
errors.push('Invalid phone number');
}

if (errors.length > 0) {
alert(errors.join('\n'));
return;
}

// Build update object
const updates = { callback: handleUpdateResult };

if (name) updates.name = name;
if (email) updates.emailid = email;
if (phone) updates.phno = phone;

// Show loading state
showLoading('Updating profile...');

// Send update
MoitribeSDK('my-game-id', 'updateProfile', updates);
});

function handleUpdateResult(result) {
hideLoading();

if (result.success) {
showSuccess('Profile updated successfully!');

// Clear form
document.getElementById('profile-form').reset();

// Update cached profile
if (result.playerdata) {
currentPlayer = result.playerdata;
displayProfile(currentPlayer);
}
} else {
showError('Update failed: ' + result.msg);
}
}

function isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

function isValidPhone(phone) {
return /^\+?[1-9]\d{9,14}$/.test(phone);
}

Best Practices

1. Validate Before Updating

Always validate input before calling updateProfile():

function validateAndUpdate(name, email) {
// Validate name
if (name.length < 3 || name.length > 20) {
showError('Name must be between 3 and 20 characters');
return;
}

// Validate email
if (!isValidEmail(email)) {
showError('Please enter a valid email address');
return;
}

// Proceed with update
MoitribeSDK('my-game-id', 'updateProfile', {
name: name,
emailid: email,
callback: handleResult
});
}

2. Provide User Feedback

Show loading states and results:

function updateProfile(updates) {
// Show loading indicator
const button = document.getElementById('update-button');
button.disabled = true;
button.textContent = 'Updating...';

MoitribeSDK('my-game-id', 'updateProfile', {
...updates,
callback: (result) => {
// Re-enable button
button.disabled = false;
button.textContent = 'Update Profile';

// Show result
if (result.success) {
showNotification('Profile updated successfully!', 'success');
} else {
showNotification('Update failed: ' + result.msg, 'error');
}
}
});
}

3. Update Local Cache

Keep your local profile data in sync:

let currentPlayer = null;

function updatePlayerProfile(updates) {
MoitribeSDK('my-game-id', 'updateProfile', {
...updates,
callback: (result) => {
if (result.success) {
// Update local cache with new values
if (result.playerdata) {
// Full profile returned
currentPlayer = result.playerdata;
} else {
// Manual update of cached profile
if (updates.name) currentPlayer.name = updates.name;
if (updates.emailid) currentPlayer.emailid = updates.emailid;
}

// Refresh UI
updateGameUI();
}
}
});
}

4. Rate Limiting

Prevent excessive update requests:

let lastUpdateTime = 0;
const UPDATE_COOLDOWN = 5000; // 5 seconds

function updateWithRateLimit(updates) {
const now = Date.now();

if (now - lastUpdateTime < UPDATE_COOLDOWN) {
const remaining = Math.ceil((UPDATE_COOLDOWN - (now - lastUpdateTime)) / 1000);
alert(`Please wait ${remaining} seconds before updating again`);
return;
}

lastUpdateTime = now;

MoitribeSDK('my-game-id', 'updateProfile', {
...updates,
callback: handleResult
});
}

5. Handle Network Errors

Provide retry options for failed updates:

function updateProfileWithRetry(updates, retries = 3) {
MoitribeSDK('my-game-id', 'updateProfile', {
...updates,
callback: (result) => {
if (result.success) {
console.log('Profile updated successfully');
} else if (retries > 0) {
// Retry on network error
console.log(`Update failed, retrying... (${retries} attempts left)`);
setTimeout(() => {
updateProfileWithRetry(updates, retries - 1);
}, 2000);
} else {
console.error('Update failed after multiple attempts');
showError('Unable to update profile. Please try again later.');
}
}
});
}

Next Steps

Related topics: