1

I have a parent component which has a state containing an array of object:

function ParentComponent(props) {
    const [objects, setObjects] = React.useState([...props.objects]);

    const handleObjectRefresh = () => {
        /**
         * Refresh objects
         */
        setObjects([
            ...newObjects
        ])
    }

    return (
        <div>
            <Button onClick={handleObjectRefresh} >Refresh</Button>
            {objects.map((obj, index) => {
                return(
                    <ChildComponent obj={obj} />
                )            
            })
        }
        </div>
    )
}

function ChildComponent(props){
    const [objParam1, setObjectParam1] = React.useState(props.obj.param1);
    const [objParam2, setObjectParam2] = React.useState(props.obj.param2);

    useEffect(()=> {
        setObjectParam1(props.obj.param1);
        setObjectParam2(props.obj.param2);
    }, [props.obj])

    return (
        <div>
            <Texfield defaultValue={objectParam1}/>
            <Texfield defaultValue={objectParam2}/>
        </div>
    )
}

My issue is right now the current default values of Textfield does not get updated if an object is removed, the object does change in the child component however, the textfield default value are the previous state, I was wondering how can I completely change the child state when the object list in the parent component changes?

EDIT

To fix the issue, I simply changed defaultValue to value

ashes999
  • 1,234
  • 1
  • 12
  • 36
  • Try changing the dependency array to `[ props.obj.param1, props.obj.param2 ]`. – BenM Apr 19 '21 at 16:47
  • 1
    I think this question has the answer you desire: https://stackoverflow.com/questions/30727837/react-change-input-defaultvalue-by-passing-props – LMulvey Apr 19 '21 at 16:48

0 Answers0