Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React array not changing with setState

My array isn’t getting new entries added to it via the setState getter.

Code:

let calledOut = false;
export default function PayStation () {
    const [records, setRecords] = useState([]);

    // problem snippet
    if (records.length === 0 && !calledOut) {
        calledOut = true;
        fetch('http://localhost:5000/api').then(
            response => response.json()
        ).then(
            data => {
                const payloadRecords = data["records"];
                // returning
                //     [{
                //         "attributes": {
                //             "type": "Contact",
                //             "url": "/services/data/v42.0/sobjects/Contact/0030U00001UPWYKQA5"
                //         },
                //         "Id": "0030U00001UPWYKQA5",
                //         "Name": "Contact25 Sequence Contact Manual Email"
                //     },
                //     {
                //         "attributes": {
                //             "type": "Contact",
                //             "url": "/services/data/v42.0/sobjects/Contact/0030U00001UPWYLQA5"
                //         },
                //         "Id": "0030U00001UPWYLQA5",
                //         "Name": "Contact26 Sequence Contact Manual Email"
                //     }
                // ]
                setRecords((records => [...records, ...payloadRecords]));
                console.log("records size: " + records.length); // why is this still 0?
            }
        );
    }
    // end problem snippet

    return (records.length === 0 ? "loading..." :
        <div style={{
            height: '100vh',
            display: 'flex',
            maxWidth: 600,
            justifyContent: 'space-between',
            alignItems: 'center'
        }} >
            {records}
        </div>
    );
}

I think the requirement for state to change is that you clone the state variable (which I believe I’m doing), as opposed to assigning a reference to it and mutating the reference.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, why isn’t my array getting new entries?

>Solution :

The body of the component should be a pure function. Side effects (such as data fetching) should be wrapped in useEffect. The following code should work:

export default function PayStation () {
  const [records, setRecords] = useState([]);

  useEffect(() => {
    const getRecords = () => {
      fetch('http://localhost:5000/api').then(
        response => response.json()
      ).then(
        data => {
          const payloadRecords = data["records"];
          setRecords((records => [...records, ...payloadRecords]));
        }
      );
    }
    
    getRecords()
  }, [])
  
  if (records.length === 0) return "loading..."

  return (
    <div style={{
      height: '100vh',
      display: 'flex',
      maxWidth: 600,
      justifyContent: 'space-between',
      alignItems: 'center'
    }} >
      {records.map((record) => <Record key={record.id} {...record} />)}
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading