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

Array isn't filled with object in Javascript

So after the content is loaded in the website I’m trying to call a function to fill [fields] (State) with the events but something Isn’t working.

Here is what I mean:

const [events, setEvents] = useState([]);

useEffect(() => {
    if (orders.orders !== null && orders.isLoading !== true)
      orders.orders.map((order) =>
        setEvents([
          ...events,
          {
            title: `Meeting with ${order.customer.firstName}`,
            date: `${order.appointment}`,
          },
        ])
      );
    setLoading(false);
  }, [orders]);

So when I console log the events, I get [] (empty), but if i console.log the object it works.

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

>Solution :

I’m not sure what you are trying to achieve with the code but looks like your useEffect has a missing dependency of events. Since you are also updating events with setEvents, you should update with

setEvents(prev=>[
  ...prev,
   {
     title: `Meeting with ${order.customer.firstName}`,
     date: `${order.appointment}`,
    }
])

to avoid an infinite loop.

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