Home > Software engineering >  Finding an array item in state
Finding an array item in state

Time:07-13

I have the following array in my Sate:

this.state = {
currentAsset: null,    
assets: [
    { id: uuidv4(), selected: false, text: 'Sorte',},
    { id: uuidv4(), selected: false, text: 'optical_dillusion2322.jpg'},
    { id: uuidv4(), selected: false, text: 'man_read_abook3242332.jpg'},

] }

I want to find one of these assets and assign it to currentAsset. I have the following function:

handleAssetIDChange(assetID) {
    console.log(assetID)
    var currentAsset = this.state['assets'][assetID]
    console.log(currentAsset)
    // this.setState({
    //     currentAsset: this.state['assets'][assetID],
    //     openAssetSideBar: true
    // }, () => {
    //     console.log(this.state['assets'][assetID])
    // })
}
              

You can see the commented out part is now working. I am trying to set the currentAsset and then trigger the open of the sidebar to display the contents, but currentAsset is not getting set.

I have the assetID, how can I locate the one I need? Another question i have is in many stackoverflow posts they reference state vars like objects, aka:

this.state.assets but I always get an error when trying to do that.

How can I assign currentAsset and then trigger the openAssetSidebar when it has been set?

CodePudding user response:

I would use a filter use get the object, this should update your currentAsset in the state.

handleAssetIDChange(assetID) {
    console.log(assetID)
    var currentAsset = this.state['assets'].filter( item => item.id === assetID)[0]
    console.log(currentAsset)
     this.setState(( prev ) => {
         ...prev,
         currentAsset,
         openAssetSideBar: true
     })
}

CodePudding user response:

In order to find the asset that you are looking for with a specific id, instead of

var currentAsset = this.state['assets'][assetID]

You should do:

const foundAsset = this.state['assets'].find((el) => el.id === assetID)

then to update the state, you would do:

this.setState((prev) => ({...prev, currentAsset: foundAsset}))
  • Related