Brian
Brian

Reputation: 169

Object array not printing to screen - React

On page load, I am using UseEffect to take an object array files. The array is mapped through, if it is male it is added to maleArray, if it is female it is added to femaleArray. At the end, i use console.log to check if the new arrays have filled and they have. I also set hasLoaded to true after this.

const[hasLoaded, setHasLoaded] = useState();
var maleArray= [];
var femaleArray= [];

useEffect(() => {
      getPersonGender();
      
    }, [props.files]);

    const getPersonGender = () => {
      if(!props.files.length > 0){
        console.log("WAITING");
      }else{
        props.files.map( person => {
          if(person.gender=== "male"){
            maleArray.push(person);
          }else{
            femaleArray.push(person);
          }
        });
        console.log(maleArray)
        console.log(femaleArray)
        setHasLoaded(true);
      }
    }

However when I get to the return statement, the new arrays I filled seem to be empty. For example, I am trying to map the maleArray to a table. I check hasLoaded and it is true but when I get to print nothing displays and I can't figure out why. When I attempted to debug, it seemed that maleArray and femaleArray never filled, but however, I am getting the console.log results saying that they are.

{!hasLoaded
    ?<div class="spinner-border" role="status"></div>
    :
    <table class="table">
    <tbody>
        {maleArray.map(male=> (
            <tr>
                <td>{male.name}</td>
                <td>{male.age}</td>
            </tr>
    ))}
    </tbody>
    </table>
}

Any reason why the new arrays are not being filled, yet i see the output on console.log? Thanks

Upvotes: 0

Views: 769

Answers (2)

SARAN SURYA
SARAN SURYA

Reputation: 554

The main reason it did not work is that the state was not set. You need to use the useState() hook to assign it to arrays and then use them further

Complete working example


import { useState, useEffect } from "react";

function ConfigurationList(props) {
  const [hasLoaded, setHasLoaded] = useState();
  // usage of hooks
  const [maleArray, setMaleArr] = useState([]);
  const [femaleArray, setFemaleArr] = useState([]);

  useEffect(() => {
    getPersonGender();
  }, [props.files]);

  const getPersonGender = () => {
    let maleBuf = [];
    let femaleBuf = [];
    if (!props.files.length > 0) {
      console.log("WAITING");
    } else {
      props.files.map((person) => {
        if (person.gender === "male") {
          maleBuf.push(person);
        } else {
          femaleBuf.push(person);
        }
      });
      console.log(maleArray);
      console.log(femaleArray);
      // Setting the value to the state
      setFemaleArr([...femaleBuf])
      setMaleArr([...maleBuf])
      setHasLoaded(true);
    }
  };

  return (
    <div>
      <div class="card rounded-0">
        <div class="card-header bg-dark custom-font rounded-0">Male</div>

        <div class="card-body text-center">
          {!hasLoaded ? (
            <div class="spinner-border" role="status"></div>
          ) : (
            <table class="table">
              <thead>
                <tr>
                  <th style={{ width: "30%" }} scope="col">
                    Name
                  </th>
                  <th style={{ width: "30%" }} scope="col">
                    Age
                  </th>
                </tr>
              </thead>
              <tbody>
                {maleArray.map((male) => (
                  <tr>
                    <td>{male.name}</td>
                    <td>{male.age}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}

export default ConfigurationList;

useState : You will have to make sure that the array is not directly updated, because that will not render the data, So you should create a local variable and then assign it to the state at the end, or you can use the spread operator and then assign them, Both should work.

Upvotes: 1

Luke V
Luke V

Reputation: 1

I think you have typo in {maleArray.map(male=>

Shouldn't it be { maleArray.map((male) => { rest of code }

Upvotes: 0

Related Questions