Home > Software design >  What's the correct way to initailise empty states in react with typescript
What's the correct way to initailise empty states in react with typescript

Time:10-17

I'm quite new to react and was wondering what was the correct way to initialise empty state variables in react. Currently I have a form in typescript which has several fields to fill. Most of those fields are dropdowns and i've initialised some static data as an array of objects something like this.

export const options = [
    {
        id : 0,
        name : "Setting 1"
    },
    {
        id : 1,
        name : "Setting 2"
    },
    {
        id : 2,
        name : "Setting 3"
    }

];

So I'm able to display these options it in the dropdown of the form and everything is working as expected. Problem comes when i try and initialise the state that I'm using to check up on the updates on this field.

const [myForm, setMyForm] = React.useState({
        dropdown : options[0],
        dropdown1 : options1[0]
    });

So for me in the myForm object that I've cerated to keep track of the state, I get the first option by default as selected as I've specified. I cannot initialise it to null as typescript requires a type for any declaration. What's the best practice to initially have the value as an empty object, and set it later when the user checks the option from the dropdown. Because if i set it to an empty object like {} in the options i cannot access the id and the name fields in the code. Can anyone tell me what's the correct way to do it

CodePudding user response:

useState can take a type. This is good for when Typescript can't infer the type from the type of the initial value. This is often the case with any null default value. You need to tell typescript what the value could be when it's not null.

For example:

const [name, setName] = useState<string | null>(null)

// name is of type: string | null
if (name != null) console.log(name.toUpperCase())

I don't entirely follow your code here, but I think you may want to set your state's type like this, with a value as an optional. This means it's allowed to be missing or undefined.

interface State {
  dropdown: FormField
  dropdown1: FormField
}

interface FormField {
  id: number
  name: string
  value?: string
}

And then use that type:

const [myForm, setMyForm] = React.useState<State>({
  dropdown : options[0],
  dropdown1 : options1[0]
});

myForm.dropdown.name // allowed, and type is: string | undefined
  • Related