I am trying to set the state of of a an object (teethData.data) in react based on the props passed into the component (props.toothData). if the props passed object has length zero then it sets. If props.toothData is length zero then a default value is given to a variable givenToothData so that teethData.data has a default value otherwise, teethData.data is just set to props.toothData. However teethData.data doesn't change the way i want it too if props.ToothData isn't length zero
Below is my code, is there any advice?
function TableArray(props) {
const navigate = useNavigate();
console.log(props.toothData);
var givenToothData = props.toothData;
if (Object.keys(props.toothData).length === 0) {
console.log("this happened", props.toothData);
givenToothData = {
1: {
pp: false,
C14: false,
GI0: false,
GI23: false,
PDI: false,
GR: false,
F13: false,
M03: false,
},
2: {
AB: false,
AT: false,
EH: false,
TI: false,
TLUX: false,
O: false,
GH: false,
OST: false,
ONF: false,
FX: false,
CA: false,
OM: false,
D: false,
DX: false,
},
3: { RTR: false, TR: false, SN: false, TA: false },
4: {
TFXUCF: false,
TFXCCF: false,
TFXUCRF: false,
TNE: false,
TPE: false,
},
}
console.log("this happened", givenToothData);
}
const [teethData, setTeethData] = useState({
tooth: props.tooth,
data: givenToothData
});
console.log(teethData.data, "runthisfirst \n", givenToothData, props.teethData);
Argument of useState hook is assigned only once when your component first mounted. On the subsequent function execution it won't set that value. Try using useEffect to set the state whenever your props change. i.e., useEffect(() => { // your logic to update state },[props.toothData]).