1
export interface JobListing {
  id: number,
  isTraded: boolean,
  feedback: string,
  title: string,
  message: string,
  skills: string[],
  sender: string,
  ipAddress: string
}


const GroupList = () => {

const [jobListings, setJobListings] = useState<JobListing[]>([]);

  useEffect(() => {
    database.collection("job_listings").onSnapshot((snapshot: any) => (
      setJobListings(snapshot.docs.map((doc: any) => doc.data()))
    ));
    alert(jobListings[0].message)
    return () => {
    }
  }, [])

  return ('JSX code')
}
export default GroupList;

I have useEffect where I am setting my listings by useState hook from firebase. Everythink works fine when I am using map to iterate over jobListings and returning table cell for each one in JSX component. However whenever in code I want access jobListings[some_index].message I am getting Cannot read property 'message' of undefined. For example in alert in code. As you see I am using typescript and have type for jobListings. When I set up instead empty array some item with appropriate properties, I was able to access index 0 jobListings[0].message.

1 Answers1

0

In your snippet, the problem is that your onSnapshot callback runs after alert. If you want to print the first item of the array, do that in the onSnapshot callback itself

useEffect(() => {
    database.collection("job_listings").onSnapshot((snapshot: any) => (
      const data = snapshot.docs.map((doc: any) => doc.data())
      setJobListings(data)
      // `jobListings` is still empty at this point, it's updated at the next render cycle
      alert(data[0].message)
    ));
    return () => {
    }
  }, [])
Luca Faggianelli
  • 2,032
  • 20
  • 23
  • I want it printed in return in GroupList functional component, its inside ModalChild passed as props, I can jobListings.map((postDetail: any, index: any) => {postDetail.message} but can't access by index, alert was just example, it should be rerendered in return – Jurgen Swensen Aug 21 '20 at 14:21
  • sorry, but I don't understand what you mean, can you show me more of your code? in the `return` statement of GroupList component you can indeed return JSX code of the jobListings, i.e.: `return
    {jobListings[0].message}
    `. Is this failing? You said something about props, are you passing props to GroupList component and it's not updating?
    – Luca Faggianelli Aug 21 '20 at 14:52
  • I have found that jobListings[0]?.message works. How can I solve it without ? with typing? – Jurgen Swensen Aug 21 '20 at 20:46
  • As per your code, you shouldn't need the `?`, though try to add a `if (jobListings.length) {}`, or in JSX `{jobListings &&
    {jobListings[0].message}
    }`
    – Luca Faggianelli Aug 24 '20 at 13:59