Home > Net >  Array isn't filled with object in Javascript
Array isn't filled with object in Javascript

Time:03-14

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.

CodePudding user response:

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.

CodePudding user response:

You are directly updating state so it is shown in console but in react rerender should be done to update state so pass parameter for setEvents and spread parameter but not directly events because you cannot directly update state.

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