/    Sign up×
Bounties /Pin to ProfileBookmark

Getting error when adding user in react js

“i am working on project and i have to add user in react js with api endpoints. i have tested the api on postman and it added new user but when i write code and try it doesnt working.

import React, { useState } from “react”;

const AddUser = ({ setTokenValue }) => {

const [isSubmitting, setIsSubmitting] = useState(false);

const [errorMessage, setErrorMessage] = useState(“”);

const [name, setName] = useState(“”);

const [email, setEmail] = useState(“”);

const [phone, setPhone] = useState(“”);

const [password, setPassword] = useState(“”);

const handleSubmit = async (event) => {

event.preventDefault();

setIsSubmitting(true);

try {

const response = await fetch(“https://api.store.ellcart.com/users”, {

method: “POST”,

headers: {

“Content-Type”: “application/json”,

“Authorization”: `Bearer <eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FwaS5zdG9yZS5lbGxjYXJ0LmNvbS91c2Vycy9sb2dpbiIsImlhdCI6MTY4NTYzNDY1MCwibmJmIjoxNjg1NjM0NjUwLCJqdGkiOiJBZ2doWFpiT1VxeGF4QTBvIiwic3ViIjoiMjA0IiwicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9.28tizEstlORenFGcDin-3RSFgtHzJpnoA2UYI7A2sJ0>`,

},

body: JSON.stringify({

name: name,

email: email,

phone: phone,

password: password,

}),

});

if (!response.ok) {

throw new Error(“Failed to add user”);

}

const data = await response.json();

if (data && data.authorisation && data.authorisation.access_token) {

const token = data.authorisation.access_token;

setTokenValue(token);

setName(“”);

setEmail(“”);

setPhone(“”);

setPassword(“”);

setErrorMessage(“”);

}

} catch (error) {

setErrorMessage(error.message);

console.error(“Failed to add user:”, error);

} finally {

setIsSubmitting(false);

}

};

return (

<form onSubmit={handleSubmit}>

{errorMessage && <p>{errorMessage}</p>}

<label>

Name:

<input type=”text” value={name} onChange={(e) => setName(e.target.value)} />

</label>

<label>

Email:

<input type=”email” value={email} onChange={(e) => setEmail(e.target.value)} />

</label>

<label>

Phone:

<input type=”phone” value={phone} onChange={(e) => setPhone(e.target.value)} />

</label>

<label>

Password:

<input type=”password” value={password} onChange={(e) => setPassword(e.target.value)} />

</label>

<button type=”submit” disabled={isSubmitting}>

{isSubmitting ? “Submitting…” : “Add User”}

</button>

</form>

);

};

export default AddUser;`

to post a answer
JavaScriptReact

2 Replies

Davinci•003 auto-replyError messages can be difficult to debug, but there are a few steps you can take to help narrow down the cause. First, check the console for any errors that may have been thrown. If there are any, look for clues as to what may have caused the error. Additionally, you can use the React DevTools to inspect the component tree and see if any components are not rendering correctly. Finally, you can use a debugging tool such as the React Profiler to identify any performance issues that may be causing the error.


// Example code for adding a user
const addUser = (user) => {
return fetch('/api/users', {
method: 'POST',
body: JSON.stringify(user),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
}

Was this helpful?

Copy linkTweet thisAlerts:
@abdulimAug 14.2023 — Are you sure you want to be storing the API bearer token client side like that? Perhaps you should send the username and password details to your server which then has the API credentials to make the request.


Currently, with React, you Authorisation Bearer token will be visible to any user and can easily be misused.
×

Success!

Help @royal125 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ,
analytics: Fullres
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Marika,
tipped: article
amount: 1000 SATS,

tipper: @hatem774,
tipped: article
amount: 1 SATS,

tipper: @nearjob,
tipped: article
amount: 1000 SATS,
)...