0

I am trying to use useState in React Native to store and display data but the array is displaying empty: Here's my data which I am trying to store:

Array [
  Object {
    "text": "Dhananjay",
    "time": 1610528730258,
  },
  Object {
    "text": "Abhey",
    "time": 1610529549681,
  },
  Object {
    "text": "Himanshu",
    "time": 1610529566017,
  },
]

Below is my code:

const [list, setList] = useState([]);

useEffect(() => {
        const items = firebase.database().ref("userName");
        items.on("value", datasnap => {
          //console.log(Object.values(datasnap.val()));
          console.log(list);
          setList([...list, {
              id: Object.values(datasnap.val())
            }
          ]);
          console.log(list);
        })
        console.log(list);
    }, []);
  • 1
    useState is `async`, so you'll not have immediate access to your updated `list` – dbuchet Jan 13 '21 at 09:49
  • Duplicate of [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Guy Incognito Jan 13 '21 at 09:52
  • Using those methods also not working, I also waited for couple of minutes to reflect those changes, but also empty array is getting printed. – Dhanjay Bhardwaj Jan 13 '21 at 10:28

1 Answers1

0

Firstly, useEffect in this instance will trigger your function anytime:

  • The functional component mounts, and
  • One of the dependencies specified in your array has changed between a subsequent re-render

Since you haven't specified any dependencies, the best way to check whether this is working is to instead render the contents of the list inside your component and observe whether the list has changed.

It is also worth noting that useState is asynchronous and you could consider using:

useEffect(() => { console.log(list)}, [list])

Alternatively, you could also try rendering the contents as well (although you've covered your bases above) with:

return (
   <div>
      {JSON.stringify(list)}
   </div>
)

And see if the text appears in the component. If it doesn't chances are the on callback isn't firing here.

Josh
  • 26
  • 5
  • Yes, I tried in react native using {JSON.stringify(list)}. The data is displaying on page but using console.log(list) displays empty array like Array[] ? – Dhanjay Bhardwaj Jan 13 '21 at 12:00
  • Yes, that's because in your JS thread on React Native the state isn't updating before the end of the useEffect function, it's asynchronous. There's nothing further you need to do as the data is correctly appearing in your interface. Is there something else you wanted to do? – Josh Jan 13 '21 at 12:07
  • No, that's fine and working for now. Thanks! – Dhanjay Bhardwaj Jan 14 '21 at 05:41
  • 1
    Awesome! Onwards and upwards! – Josh Jan 14 '21 at 09:54