Search code examples
reactjstypescriptreact-nativereduxgetderivedstatefromprops

How to compare two objects value by iterating if both have same name in getDerivedStateFromProps?


The props coming from react is account and I'm keeping a copy of it as previousProps, before setting it to the state I need to compare each and every object and assign the value to state if both props object are different. However, both previous props and redux props are of same kind. Is there any way to iterate over it rather than writing one by one below.

static getDerivedStateFromProps(nextProps: Props, prevState: State) {
    console.log("getDerivedStateFromProps");

    Object.keys(nextProps.account).every((key) => {
    // can i compare both keys with a loop.
        if (nextProps.account.firstName !== prevState.previousProps.firstName) {
            console.log("different");
            return {
                previousProps: nextProps,
                userInfo: nextProps,
                personalInfo: {
                    first_name: nextProps.account.firstName,
                },
            };
        }
    });

    if (nextProps.account.firstName !== prevState.previousProps.firstName) {
        console.log("different");
        return {
            previousProps: nextProps,
            userInfo: nextProps,
            personalInfo: {
                first_name: nextProps.account.firstName,
            },
        };
    }

    if (nextProps.account.lastName!== prevState.previousProps.lastName) {
        console.log("different");
        return {
            previousProps: nextProps,
            userInfo: nextProps,
            personalInfo: {
                last_name: nextProps.account.lastName,
            },
        };
    }
    return null;
}

Solution

  • I think you can do it like this;

    Object.keys(nextProps.account).every((key) => {
        if (nextProps.account[key] !== prevState.previousProps[key]) {
            return {
                previousProps: nextProps,
                userInfo: nextProps,
                personalInfo: {
                    [key]: nextProps.account[key],
                },
            };
        }
    });