Skip to content
Advertisement

setState to update an interface array

I need to update an array of address inside the User interface. I am trying to use setState to update the address from UI form. I have tried the following:

setUser({...user, address: [...(user?.address|| []), addressObject]});

However I am getting the following error: Type ‘Address | undefined’ is not assignable to type ‘Address’.   Type ‘undefined’ is not assignable to type ‘Address’.

export default interface User{

    firstName: string,
    surName: string,
    email: string,
    phone: string
    Address: Address[]
}

any help would be much appreciated

Advertisement

Answer

Make sure that your address prop is defined before you set it to the state. You can do that in the following fashion:

if (user.address){
    setUser({...user, address: [...(user.address|| []), addressObject]});
}

ts will pick up that user.address will be defined by the time the setState is being called.

OR, if you want to allow address to be undefined, then you can change the interface definition to:

export default interface User{
    ...
    Address: Address[] | undefined
}

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement