I have a Typecript- based React component that performs an asynchronous “create” operation. Once that operation is successfully completed, I want to be able to update some other components using the created object.
What I am trying to do is represented below. I am attempting to perform the following actions in sequence:
Create Data (User Object) --->Send "create" request --> Return the object to another component-->Do something with the object
The data I am creating is below:
interface User {
firstName: String;
lastName: string;
}
const aUser: User = {
firstName: 'James',
lastName: 'Kirk',
}
I am using Axios to request a server to create the user record in a database:
export const createUser = async (nwUser: NetUser) => {
const response = await userKey.post<IResult>('/user/create',nwUser);
return response.data;
}
The code that calls the request function is below. Note that I am attempting to save the aUser object, then return it to the calling function.
function doSubmit(isNew: boolean): aUser {
let userpromise;
if(isNew) {
userpromise = addUser();
else
userpromise = performSomeOtherAction();
userpromise.then((user)=> return(user));
}
async function addUser(): Promise<User> {
const result = createUser(aUser);
result.then((value) =>{
const name = changeObj.firstName+" "+changeObj.lastName;
if(value.success)
alert(name+" was successfully added");
else
alert("Add of "+name+" failed: "+value.message);
return aUser;
});
}
Ultimately, what I am trying to do is to call the doSubmit() function from a parent component, which uses useRef() to
access doSubmit. the parent makes the doSubmit call:
const user = doSubmit(true);
so that I can do things with the user object.
Unfortunately, the code as I have written it does not work. I cannot seem to make the addUser() function return the User promise.
Is there a way to do this? How can I make a function like addUser return the promise for an object that exists within a component?