Home > Software design >  Deep copy data update problem in react native
Deep copy data update problem in react native

Time:11-26

I am using this

    const HomeProfile = ({data}) =>{
    var tempData = {}
    
const onOptionClick = ( clicked_index) => {
    tempData = { ...data[0].atpData }
    tempData.selected_index = clicked_index
  }

const addInProps = () =>{
data[0].atpData=tempData
}

const checkData = () =>{
console.log('tempData',tempData)
}

    return(
    <View>
    <Text></Text>
    </View>
    )
    }

When check data in checkData function it is giving me the empty data. But if i am using this hooks like

const [tempData,settempData] = usestate({})

My Problem: It is working good as i am using it with var tempData = {} but problem in that after adding data. Still getting empty Data in the checkData() functions

If i am using with const [tempData,settempData] = usestate({}) then it is changing my data in the data[0].atpData without hitting the function so i am not getting how to resolve it. But i am getting data checkData() function as i required.

CodePudding user response:

You should use useState hook, so you need initialize it as empty object, and call setter inside your method as you desire:

const HomeProfile = ({data}) =>{
    const [tempData, setTempData] = useState({})
    
const onOptionClick = ( clicked_index) => {
    setTempData({...data[0].atpData, selected_index: clicked_index})

  }

const addInProps = () =>{
data[0].atpData=tempData
}

const checkData = () =>{
console.log('tempData',tempData)
}

    return(
    <View>
    <Text></Text>
    </View>
    )
    }

CodePudding user response:

you can use useEffect hook when detect the object change

  • Related