简体   繁体   中英

Updating local state with react hooks

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>
    )
}

simple you just use the variable feeds, provided you have defined it BEFORE using it. you have used it correctly with an error that updating you are not setting state to the updated feeds variable

 let updatedFeeds = feeds.filter( feed => feed.id != feedId )
 setFeeds(updatedFeeds) // you were setting it to the old unchanged feeds variable

remember filter function never modifies the original variable it always creates a new object which is modified

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM