2

I want to store an object in the react state with useState and pass setState down to a child component, but then I get an typescript error. What is wrong?

typescript Error

Argument of type '(oldPerson: any) => any' is not assignable to parameter of type 'Person'.

Code

interface Person {
name: string
age: number
job: string

}

const [person, setPerson] = useState<Person | null>()

const updateOldPerson={
  age: 70
}
    
setPerson((oldPerson) => ({
      ...oldPerson,
      ...updateOldPerson
 }))
4
  • 1
    are you calling setPerson in the same component? If you're passing it as props make sure that the props interfaces have the correct type. Commented Aug 19, 2021 at 15:53
  • 1
    useState<Person | null>() should be useState<Person | undefined>() Commented Aug 19, 2021 at 15:55
  • @RameshReddy I send the setState down to a child component. why is "null" not good? Commented Aug 19, 2021 at 16:02
  • 1
    If you want to use null then the initial state should be like useState<Person | null>(null). Add the props interface of the child component to the question. Commented Aug 19, 2021 at 16:05

2 Answers 2

2

If you want to use null type then the initial state shouldn't be undefined

const [person, setPerson] = useState<Person | null>(null)

In order to use both functional state update and normal state update, the type of setPerson can be

setPerson: Dispatch<SetStateAction<Person | null>>;

if you're passing this as a prop to a child component, the props interface should look like this

interface ChildProps {
  setPerson: Dispatch<SetStateAction<Person | null>>;
}


const Child: FunctionComponent<ChildProps> = ({ setPerson }) => {
  return (
    <button
      onClick={() => {
        const updatedPerson = {
          name: "vuvu",
          age: 69,
          job: "foo"
        };
        setPerson((prevPerson) => ({ ...prevPerson, ...updatedPerson }));
      }}
    >
      Update Person
    </button>
  );
};

Here's a working codesandbox example

and as the age, name, job properties are not optional, make sure that you update the state with a person object that has all three fields. Alternatively, you can make some fields optional, like

interface Person {
  name: string;
  age: number;
  job?: string; // this is optional
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for that great answer. In my case I only wanted to update the age, I didn't know that the fields need to be optional in the interface
0

You need to add some conditional logic in your setPerson call, the reason why is because the state can be null, and if you spread a null value in an empty object it will return the empty object, so you won't be passing the required person attributes, just the age:

// Set this to null to infer better the types, usually useState() 
// means setting the state to undefined
const [person, setPerson] = React.useState<Person | null>(null);

After that you should add some logic inside your setState call to verify that you actually have a Person and not a null value:

const updateOldPerson = {
  age: 70
};

setPerson((oldPerson) => {
  if (oldPerson == null) {
    // You need to explicitly pass the Person attributes here because the state value is null
    return {
     ...updateOldPerson,
     name: "John",
     job: "N/A"
    };
  }

  return {
    ...oldPerson,
    ...updateOldPerson
  };
});

Check this sandbox to verify the behavior: https://codesandbox.io/s/frosty-swirles-152fu?file=/src/App.tsx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.