Atualizar atributos do usuário, como o número de telefone
Atualiza os atributos de um usuário, como o número de telefone.
O que este exemplo faz:
- Autentica o usuário com login e senha
- Obtém os dados do usuário atual para preencher previamente o formulário no frontend
- Permite que o usuário edite um campo (por exemplo, o telefone) e o salva
- Salva os dados na OneEntry Platform
Pré-requisitos:
- Um PROJECT_URL e um APP_TOKEN válidos para a API do OneEntry.
- Um formulário de cadastro com o marcador "reg"
- Campos do formulário (atributos) com os marcadores "email_reg", "password_reg", "name_reg", "phone_reg"
- Um usuário existente e ativado para autenticar
Observações:
- Os exemplos tratam erros de forma mínima: verificam se há um objeto de erro e param.
- Por padrão (
isShell: true), o SDK retorna um objeto de erro em vez de lançar uma exceção, então verifique o resultado, por exemplo'statusCode' in result. ComisShell: false, ele lança a exceção, e você trata os erros com try/catch. Veja Erros. - O formIdentifier passado para updateUser() deve corresponder ao configurado no seu projeto OneEntry.
Documentação da plataforma:
Referência do SDK:
Experimente ao vivo
Execute este exemplo no sandbox do JS SDK. Conecte a URL do seu projeto e o App Token na primeira visita e, em seguida, abra:
Cenário
Os passos abaixo são trechos do componente React do Exemplo final. O estado, as credenciais e os helpers, como emailReg, passwordReg, values, fields, prepareValue e displayValue, estão definidos lá.
1. Importar defineOneEntry e definir PROJECT_URL e APP_TOKEN
import { defineOneEntry } from 'oneentry';
const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';
2. Criar um cliente da API com defineOneEntry()
const { AuthProvider, Users } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
3. Montar o authData e autenticar o usuário com 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. Obter o usuário atual para preencher previamente o formulário com 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);
Resultado:
{
"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. Atualizar o usuário com 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;
}
Passe authData apenas para alterar a senha. A API gera novamente o hash de qualquer valor de senha que você enviar.
6. Obter o usuário atualizado com Users.getUser()
const userData = await Users.getUser();
if ('statusCode' in userData) {
setErrorMsg(userData.message);
setStatus('error');
return;
}
setUser(userData);
Resultado:
{
"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": []
}
Exemplo final
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;