Skip to content

Cannot read property ‘reduce’ of undefined data from firebase

I am trying to git the totalBalance of but i face error Cannot read property ‘reduce’ of undefined and in the same time i can iterate on the clients of the component the code is the below

//redux and firebase
import { useSelector} from 'react-redux'
import { useFirestoreConnect, isLoaded, isEmpty} from 'react-redux-firebase'
const Clients = () => {
  useFirestoreConnect(["client"]) //the name of collection  on firebase
  const clients = useSelector((state) => state.firestore.ordered.client);
  const totalBalance = clients.reduce((acc,client)=>(acc + client.balance),0)
  return (
    <div className="client">
      <div className="row client_head ">
      <div className="col">
      <FaUsers />
        <span className="ml-2">Clients</span>
      <div className="col text-right">
      <span className="d-b">Total:  </span>
        <span className="ml-auto ">
        {clients.length===0?0:clients.reduce((acc,client)=>(acc + Number(client.balance),0))}
      <div className="client_info row text-center">
          <table className="mt-3 w-100 table-bordered">
                <th>First Name</th>
                <th>Last Name</th>
              { =>
                <tr key={}>
                  <td className="p-3">3</td>
export default Clients

i thought the issue is clients is undefined but i don’t know the reson


This error is telling you that the clients object which you are selecting from redux is undefined. It might be that it starts out as undefined and then populates with the data asynchronously, so it would be undefined on the first render but fine afterwards. If it is continuing to stay undefined then there is an issue somewhere else in your code.

There are two easy ways to deal with data that might not exist yet.

  1. You can replace undefined with an empty array and render the rest of the component normally. You would have a list with no items and 0 balance.
const clients = useSelector((state) => state.firestore.ordered.client) || [];
  1. You can stop the rest of the component from rendering. Either render nothing or a render some loading screen.
const clients = useSelector((state) => state.firestore.ordered.client);
if ( ! clients ) {
    return (<div>Loading...</div>);
// the rest of the component continues below