How to delete object from array?

I'm making abillity to follow/unfollow on my page using React/Redux. And I'm not fully understand how to make this. So, when the user following 'something', reducer makes:

case FOLLOW_CITY: {
    return {
        ...state,
        followingCity: 
            [...state.followingCity,{
                id: shortid.generate(),
                cityAdded: action.city, 
                country: state.data.map(el => el.sys.country).toString(),
                name: state.data.map(el => el.name).toString(),
                followingStatus: true
            }]
    }
}

But I don't know how to make unfollow function. It has to delete object which I create above from array followingCity.

Also on the page, the title has to change:

{followingCity || followingCity.followingStatus === true // it doesnt' work
    ?   <div onClick={() => deleteCity()} className='add-button'> // how to create this?
            <span>followed</span>
            <i className="fa fa-check" aria-hidden="true"></i>
        </div>

    :   <div onClick={() => addCity(dailyData)} className='add-button'>
            <span>follow</span>
            <i className="fa fa-plus" aria-hidden="true"></i>
        </div>
}

Upvotes: 0

Views: 59

Answers (1)

user12948615
user12948615

Reputation:

You can filter the array and remove the object based on the id.

<div onClick={() => deleteCity(followingCity.id)} className='add-button'> // how to create this?
      <span>followed</span>
      <i className="fa fa-check" aria-hidden="true"></i>
</div>

Your deleteCity function can supply the id of the object and then for filtering you can do:

CASE DELETE_CITY: {
  return {
    ...state,
    followingCity: state.followingCity.filter(a => a.id !== theId)
  }
}

Upvotes: 3

Related Questions