Home > Blockchain >  How to update flatlist arrays in functional component [extraData won't work]
How to update flatlist arrays in functional component [extraData won't work]

Time:04-21

After removing an array object I expect the flatlist to update but it fails until I reload the app. Is there a way to get the update in real time?

My code:

    ...imports...

arr = [
  {id:1, name:'test1'}, 
  {id:2, name:'test2'},
  {id:3, name:'test3'},
]
export default function App() {
  const [posts, setPosts] = useState([])

  setTimeout(() => { delBet() }, 8000)
  function delBet() {
    try {
      arr.splice(arr[2], 1); setPosts(arr)
      //only remove {id:3, name:'test3'},

      console.log(arr) //works well
      //only show  [{id:1, name:'test1'},{id:2, name:'test2'}]
    } catch (e) { console.log(e) }
  }
  return (
    <FlatList
      data={posts}
      extraData={posts} //doesn't work/make any difference
      renderItem={({ item }) =>
        <Post
          post={item}
        />
      }
    />
  )
}

I'd appreciate any kind of help (including improving my code)

CodePudding user response:

Your state is mutated,

try

setPosts([...arr]); instead of setPosts(arr);

CodePudding user response:

The actual value of posts is [], if you need try to initialize the posts with the arr value, Just like this:

const [posts, setPosts] = useState(arr)

Additionally you can use setTimeout inside a use effect for render just once.

useEffect(()=> { 
  setTimeout(() => { delBet() }, 8000)
  function delBet() {
   try {
     setPosts(() => arr.splice(arr[2], 1))
   } catch (e) { console.log(e) }
  }
}, [])
  • Related