Home > Enterprise >  Initial state as an object in React
Initial state as an object in React

Time:12-06

I have a following state in React:

interface A {
   foo: string;
}

const [val, setVal] = useState<A>({});
                              // ^^^ error

However Im getting error that Im missing foo in the initial state. But I dont have any initial value for foo field.

What is the proper way to handle it?

useState<Partial<A>>({});

or 

useState<A>({} as A);

or make `foo` optional?

useState<{ foo?: string }>({});

What is the correct fix for such situation?

CodePudding user response:

You have 2 options to fix your issue.

  1. Make the foo property optional:
interface A {
   foo?: string;
}

const [val, setVal] = useState<A>({});
  1. Initialize your object with empty string:
interface A {
   foo: string;
}

const [val, setVal] = useState<A>({ foo: '' });

CodePudding user response:

I think this solution is good:

useState<{ foo?: string }>({});

Other solution is:

interface A {
 foo: string;
}

const [val, setVal] = useState<A>({ foo: '' });

CodePudding user response:

If you want to handle undefined initial state then use undefined.

interface A {
   foo: string;
}

const [val, setVal] = useState<A | undefined>();

Then you have a good chance to handle undefined inside your component. You also get help from your IDE.

  • Related