Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript useState: SetState in Child with argument

thx for any help.

How can I pass down setState to a child component and use the c argument without a typescript error?

Parent: Passing down setState

export interface State {
    value1: string;
    value2: string;
}

const Parent = () => {
    const [state, setState] = useState<State>({
        value1: "test",
        value2: "test",
    });

    return (
        <React.Fragment>
            <Child setState={setState} />
        </React.Fragment>
    );
};

export default Parent;

Child: use setState with c as argument, c is read underlined with a type error

type Props = {
    setState: Dispatch<State>;
};

const Child: React.FC<Props> = ({ setState }) => {
    return (
        <React.Fragment>
            <button
                onClick={() => {
                    //c is read underlined: Argument of type '(c: any) => any' is not assignable 
                    //to parameter of type 'State'.
                    //Type '(c: any) => any' is missing the following properties from type 
                    //'State': value1, value2
                    setState((c) => {
                        return {
                            ...c,
                            value2: "HelloWorld",
                        };
                    });
                }}
            />
        </React.Fragment>
    );
};

export default Child;
like image 740
Tölz Avatar asked Nov 07 '20 15:11

Tölz


Video Answer


1 Answers

try this, or replace <any> with your state type.

type Props = {
    setState: React.Dispatch<React.SetStateAction<any>>;
};
like image 130
Drew Cordano Avatar answered Sep 28 '22 03:09

Drew Cordano