I'm learning how to use hooks and have still a little trouble comprehending how to use local component state.
In the following component I am fetching data to display as a list. I store that in the local state and display the list.
Now I want to delete an item from the list and update the current variable in the local state that displays the data and remove the one item i just deleted.
Question: How do I use the local state variable, in this case feeds in the deleteFeed method so I can update the list. In class based components I could have just used this.state.feeds to update but how is it done in function components?
import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom'
import * as FeedsAPI from '../../../lib/feeds/FeedsAPI'
import FeedsList from './components/FeedsList'
import AddNewFeed from './components/AddNewFeed'
import DSPageLoader from '../../../components/DSPageLoader/DSPageLoader'
import FeedCard from './components/FeedCard'
const AddNewFeedCard = FeedCard(AddNewFeed)
export default function Feeds (params) {
const[feeds, setFeeds] = useState([])
const[providers, setProviders] = useState([])
const[loading, setLoading] = useState(true)
const[error, setError] = useState(false)
/**
* Method used run after evey lifecycle event
*/
useEffect( () => {
Promise.all(
[
FeedsAPI.getFeeds('id', 732),
FeedsAPI.getFeedProviders()
]
)
.then( response => {
setFeeds(response[0])
setProviders(response[1])
setLoading(false)
})
.catch( error => {setLoading(false); setError(error)})
}, [])
/**
* Update feeds in local state
*
* @param feed single feed object
*/
const updateFeed = (feed) => console.log(feed)
/**
* Delete feed
*
* @param feedId
*/
const deleteFeed = (feedId) => {
FeedsAPI.deleteFeed(feedId)
.then( response => {
let updatedFeeds = feeds.filter( feed => feed.id != feedId )
setFeeds(feeds)
})
.catch( error => console.log(error))
}
/* TODO: Refactor this to use with page loading HOC */
if (loading) {
return <DSPageLoader/>
}
return (
<div className="container">
<FeedsList
feeds={feeds}
providers={providers}
updateFeed={updateFeed}
deleteFeed={deleteFeed}
/>
<AddNewFeedCard />
</div>
)
}