Home > Net >  converting an object into an array for render
converting an object into an array for render

Time:03-16

I am trying to create a booking agent and ran into this problem where it wont let me render because the object is not being passed in.

Invalid prop items of type array supplied to ReservationList, expected object.

Here is my code

export default function CalendarScreen() {

  const [modalOpen, setModalOpen] = useState(false)
  const [items, setItems] = useState([])

  const loadItems = (day) => {
    setTimeout(() => {
      for (let i = -15; i < 85; i  ) {
        const time = day.timestamp   i * 24 * 60 * 60 * 1000;
        const strTime = timeToString(time);
        if (!items[strTime]) {
          items[strTime] = [];
          const numItems = Math.floor(Math.random() * 3   1);
          for (let j = 0; j < numItems; j  ) {
            items[strTime].push({
              name: "items",
              height: Math.max(50, Math.floor(Math.random() * 150)),
            });
          }
        }
      }
      var newItems = {};
      Object.keys(items).forEach((key) => {
        newItems[key] = items[key];
      });
      setItems(newItems);
    }, 1000);
  };

  const renderItem = (item) => {
    return (
      <TouchableOpacity style={{marginRight: 10, marginTop: 17}}>
        <Card>
          <Card.Content>
            <View
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}>
              <Text>{item.name}</Text>
            </View>
          </Card.Content>
        </Card>
      </TouchableOpacity>
    );
  };
  

I am not sure how to fix this problem.

CodePudding user response:

in propTypes change ReservationList to

ReservationList: PropType.array

CodePudding user response:

You can use this function to create array from object :

export const objectToArray = (obj: any) => {
return Object.keys(obj).map(function (key) {
    return obj[key];
});

};

  • Related