Gusta Mello
Gusta Mello

Reputation: 11

React - map() is not a function

I'm setting the values ​​in this state inside useEffect, but for some reason after some updates it starts to give an error, map() is not a function. I tried to pass a TimeOut, tried to put a ternary in the render but it still persists in the error. It's as if in the same second that it's going to update it tries to render, will anyone be able to identify where I'm going wrong?

useEffect:

  useEffect(() => {
    if (vehicle.status === 200) {
      setTotalCount(vehicle.count);
      setVehicles(vehicle.vehicles);
    }
  }, [vehicle.status, vehicle.vehicles]);

Render:

 {vehicles?.map((vehicle) => (
                <CardExplore
                  bodyVehicle={vehicle}
                  isFavorites={false}
                  termLease={termLease}
                  termFinance={termFinance}
                  key={vehicle.VIN}
                  valueDown={rangeValue}
                  valueMpy={mileage}
                  leaseToFinance={leaseToFinanceState}
                  loading={loading}
                />
              ))}

Error happening even the Results being an array.

Results is the array I'm setting in the state, you can see that it's an array and it has items inside it, but still.

Array Results being set in state.

Upvotes: 1

Views: 645

Answers (1)

Rajdeep D
Rajdeep D

Reputation: 3910

Append this vehicles && conditional check before your map to prevent this error when the array is undefined.

{vehicles && vehicles.map((vehicle) => (
                <CardExplore
                  bodyVehicle={vehicle}
                  isFavorites={false}
                  termLease={termLease}
                  termFinance={termFinance}
                  key={vehicle.VIN}
                  valueDown={rangeValue}
                  valueMpy={mileage}
                  leaseToFinance={leaseToFinanceState}
                  loading={loading}
                />
              ))}

Upvotes: 1

Related Questions