Update user attributes, such as a phone number
Updates a user's attributes, such as their phone number.
What this example does:
- Signs the user in with a login and password
- Gets the current user data to pre-fill the frontend form
- Lets the user edit a field (for example, phone) and saves it
- Saves the data in the OneEntry Platform
Prerequisites:
- A valid PROJECT_URL and APP_TOKEN for the OneEntry API.
- A registration form with marker "reg"
- Form fields (attributes) with markers "email_reg", "password_reg", "name_reg", "phone_reg"
- An existing, activated user to authenticate as
Notes:
- The examples handle errors minimally: they check for an error object and stop.
- By default (
isShell: true) the SDK returns an error object instead of throwing, so check the result, e.g.'statusCode' in result. WithisShell: falseit throws, and you handle errors with try/catch. See Errors. - The formIdentifier passed to updateUser() must match the one configured in your OneEntry project.
Platform docs:
SDK reference:
Try it live
Run this example in the JS SDK sandbox. Connect your Project URL and App Token on first visit, then open:
Scenario
The steps below are excerpts from the React component in the Final example. State, credentials and helpers such as emailReg, passwordReg, values, fields, prepareValue and displayValue are defined there.
1. Import defineOneEntry and define PROJECT_URL and APP_TOKEN
import { defineOneEntry } from 'oneentry';
const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';
2. Create an API client with defineOneEntry()
const { AuthProvider, Users } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
3. Build authData and authenticate the user with AuthProvider.auth()
const authData = [
{ marker: 'email_reg', value: emailReg },
{ marker: 'password_reg', value: passwordReg },
];
const authResponse = await AuthProvider.auth('email', { authData });
if ('statusCode' in authResponse) throw new Error(authResponse.message);
4. Get the current user to pre-fill the form with Users.getUser()
const data = await Users.getUser();
if ('statusCode' in data) throw new Error(data.message);
setUser(data);
const initial: Record<string, string> = {};
(Array.isArray(data.formData) ? data.formData : []).forEach((d: any) => {
initial[d.marker] = displayValue(d.value);
});
setValues(initial);
Result:
{
"id": 39,
"total": "1",
"identifier": "john@example.com",
"authProviderIdentifier": "email",
"formData": [
{
"marker": "name_reg",
"type": "string",
"value": "John"
},
{
"marker": "phone_reg",
"type": "string",
"value": "+12025550147"
},
{
"marker": "email_notification_reg",
"type": "string",
"value": "john@example.com"
}
],
"formIdentifier": "reg",
"groups": [
1
],
"state": {},
"rating": {},
"moduleFormConfigs": []
}
5. Update the user with Users.updateUser()
const formData = fields.map((d: any) => ({
marker: d.marker,
type: d.type,
value: prepareValue(d.type, values[d.marker] ?? displayValue(d.value)),
}));
// notificationData is left out: it replaces the stored object, including
// the FCM tokens in phonePush.
const body = {
formIdentifier: 'reg',
formData,
};
const result = await Users.updateUser(body);
if (result !== true) {
setErrorMsg(typeof result === 'object' ? result.message : 'Update failed');
setStatus('error');
return;
}
Pass authData only to change the password. The API re-hashes any password value you send.
6. Get the updated user with Users.getUser()
const userData = await Users.getUser();
if ('statusCode' in userData) {
setErrorMsg(userData.message);
setStatus('error');
return;
}
setUser(userData);
Result:
{
"id": 39,
"total": "1",
"identifier": "john@example.com",
"authProviderIdentifier": "email",
"formData": [
{
"marker": "name_reg",
"type": "string",
"value": "John"
},
{
"marker": "phone_reg",
"type": "string",
"value": "+12025550147"
},
{
"marker": "email_notification_reg",
"type": "string",
"value": "john@example.com"
}
],
"formIdentifier": "reg",
"groups": [
1
],
"state": {},
"rating": {},
"moduleFormConfigs": []
}
Final example
import { useState, useEffect } from 'react';
// 1. Import defineOneEntry and define PROJECT_URL and APP_TOKEN
import { defineOneEntry } from 'oneentry';
import type { IUserEntity } from 'oneentry';
const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';
// 2. Create an API client
const { AuthProvider, Users } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
// Prepare value for API submission by field type
function prepareValue(type: string, value: string) {
if (type === 'text') return [{ plainValue: value }];
if (type === 'list' || type === 'radioButton') return [value];
return value;
}
// Read a displayable string from a user formData entry's value
function displayValue(value: any): string {
if (typeof value === 'string') return value;
if (Array.isArray(value)) return value[0]?.plainValue ?? value[0]?.value ?? '';
return value?.plainValue ?? '';
}
// Choose a sensible input type for a field by its marker
function inputTypeFor(marker: string) {
if (marker.includes('password')) return 'password';
if (marker.includes('email')) return 'email';
if (marker.includes('phone')) return 'tel';
return 'text';
}
const UpdateUser = () => {
const [user, setUser] = useState<IUserEntity | null>(null);
const [values, setValues] = useState<Record<string, string>>({});
const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
const [errorMsg, setErrorMsg] = useState('');
// Pre-filled credentials (substituted at runtime from your settings)
const emailReg = 'your-email';
const passwordReg = 'your-password';
// 3. Build authData and sign in
useEffect(() => {
const authData = [
{ marker: 'email_reg', value: emailReg },
{ marker: 'password_reg', value: passwordReg },
];
AuthProvider.auth('email', { authData })
// 4. Get the current user to pre-fill the form
.then((auth) => {
if ('statusCode' in auth) throw new Error(auth.message);
return Users.getUser();
})
.then((data: any) => {
if ('statusCode' in data) {
setErrorMsg(data.message);
setStatus('error');
return;
}
setUser(data);
const initial: Record<string, string> = {};
(Array.isArray(data?.formData) ? data.formData : []).forEach((d: any) => {
initial[d.marker] = displayValue(d.value);
});
setValues(initial);
console.log('User ', data);
})
.catch((err: Error) => {
setErrorMsg(err.message);
setStatus('error');
});
}, []);
if (status === 'error' && !user) return <p role="alert">{errorMsg}</p>;
if (!user) return <div>Loading...</div>;
const fields = Array.isArray(user.formData) ? user.formData : [];
const handleSubmit = async (e: any) => {
e.preventDefault();
setStatus('loading');
setErrorMsg('');
// 5. Update the user
const formData = fields.map((d: any) => ({
marker: d.marker,
type: d.type,
value: prepareValue(d.type, values[d.marker] ?? displayValue(d.value)),
}));
// notificationData is left out: it replaces the stored object,
// including the FCM tokens in phonePush.
const body = {
formIdentifier: 'reg',
formData,
};
const result = await Users.updateUser(body);
if (result !== true) {
setErrorMsg(typeof result === 'object' ? result.message : 'Update failed');
setStatus('error');
return;
}
// 6. Get the updated user
const userData = await Users.getUser();
if ('statusCode' in userData) {
setErrorMsg(userData.message);
setStatus('error');
return;
}
setUser(userData);
console.log({ result, userData });
setStatus('success');
};
return (
<form onSubmit={handleSubmit}>
<h2>Update profile</h2>
{fields.map((field: any) => {
const value = values[field.marker] ?? '';
const onChange = (val: string) =>
setValues((prev) => ({ ...prev, [field.marker]: val }));
return (
<div key={field.marker}>
<label htmlFor={field.marker}>{field.marker}</label>
<input
id={field.marker}
type={inputTypeFor(field.marker)}
value={value}
onChange={(e: { target: { value: string } }) => onChange(e.target.value)}
/>
</div>
);
})}
<button type="submit" disabled={status === 'loading'}>
{status === 'loading' ? 'Saving...' : 'Save'}
</button>
{status === 'error' && <p role="alert">{errorMsg}</p>}
{status === 'success' && <p role="status">User updated!</p>}
</form>
);
};
export default UpdateUser;