DitIsVincent
DitIsVincent

Reputation: 11

Error with Mapping array React Typescript

I'm creating a list of things but it gives me the same error the whole time. that the .map function won't work on my Variable so can you guys help me out.

It's made in Typescript React. I was trying to get this to work for a hole week and still can't find the problem I even tried rewriting the hole system but still didn't work so this is my last hope.

Error

react-dom.development.js?e444:25163 Uncaught TypeError: Cannot read property 'map' of undefined
    at _default (CloudServersContainer.tsx?a799:46)
    at renderWithHooks (react-dom.development.js?e444:16240)
    at mountIndeterminateComponent (react-dom.development.js?e444:18774)
    at beginWork$1 (react-dom.development.js?e444:20136)
    at HTMLUnknownElement.callCallback (react-dom.development.js?e444:337)
    at Object.invokeGuardedCallbackDev (react-dom.development.js?e444:386)
    at invokeGuardedCallback (react-dom.development.js?e444:441)
    at beginWork$$1 (react-dom.development.js?e444:25737)
    at performUnitOfWork (react-dom.development.js?e444:24664)
    at workLoopSync (react-dom.development.js?e444:24637)

The Json that I get when I do Eggs.data

Link to the image: https://i.sstatic.net/CKC0Y.png

The Code:

import React, { componentDidMount, useEffect, useState } from 'react';
import PageContentBlock from '@/components/elements/PageContentBlock';
import Button from '@/components/elements/Button';
import Input from '@/components/elements/Input';
import InputSpinner from '@/components/elements/InputSpinner';
import tw from 'twin.macro';
import useSWR from 'swr';
import TitledGreyBox from '@/components/elements/TitledGreyBox';
import { Textarea } from '@/components/elements/Input';

export default () => {
    const [loading, setLoading] = useState(false);

    interface EggsPlace {
        Egg: String;
        run(arg: any): void;
    }

    const [Eggs, setEggs] = useState<EggsPlace>([]);

    const getEggs = async () => {
        const response = await fetch('/api/client/cloudservers/getoptions');
        if (response.status !== 400) {
            const content = await response.json();
            const data = content;
            setEggs({ data });
        }
    };

    useEffect(() => {
        getEggs();
    }, []);

    if (typeof Eggs.data !== 'undefined') {
        console.log(Eggs.data[0]);
    }



    return (
        <PageContentBlock title={'Options'} showFlashKey={'options'}>
            <h1>Server Types:</h1>
            <div css={tw`w-full grid grid-flow-col grid-rows-2 grid-cols-3 gap-4`}>
                {
                    Eggs.data !== 'undefined' ?
                        Eggs.data.map(item => (
                            console.log(item)
                        ))
                        :
                        <p>loading</p>
                }
            </div>
            <TitledGreyBox title="Configuration" css={tw`flex-wrap md:flex-no-wrap`}>
                <div css={tw`w-full grid grid-flow-col grid-rows-2 grid-cols-2 gap-4`}>
                    <div css={tw`w-full col-span-2`}>
                        <InputSpinner visible={loading}>
                            <Input
                                readOnly={false}
                                name={"Name"}
                                placeholder={"Name Server"}
                            />
                        </InputSpinner>
                    </div>
                    <InputSpinner visible={loading}>
                        <Input
                            readOnly={false}
                            name={"Memory"}
                            placeholder={"Memory"}
                        />
                    </InputSpinner>
                    <InputSpinner visible={loading}>
                        <Input
                            readOnly={false}
                            name={"Disk"}
                            placeholder={"Disk"}
                        />
                    </InputSpinner>
                </div>
                <div css={tw`mt-4 w-full`}>
                    <Textarea
                        placeholder={'Description'}
                    />
                </div>
            </TitledGreyBox>
            <Button css={tw`mt-4`} color="primary">Create Server</Button>
        </PageContentBlock>
    );
};

Upvotes: 1

Views: 225

Answers (3)

DitIsVincent
DitIsVincent

Reputation: 11

I found why it didn't work it was just I was using 'undefined' instead of undefined. Thank you all!

Upvotes: 0

Kevin Amiranoff
Kevin Amiranoff

Reputation: 14553

I believe that the issue is here:

Eggs.data !== 'undefined'

this is comparing to a string 'undefined'.

What you want is Eggs.data !== undefined or !Eggs.data or typeof Eggs.data !== 'undefined'

Also, you have some TypeScript issues I believe, if you do:

setEggs({ data });

Then you should initialize Eggs like this

    const [Eggs, setEggs] = useState<{data: EggsPlace[]}>({data: []});

That would also make sure your initialise data with an empty array. Although, it would still break if data in setEggs({ data }); is not an array.

Upvotes: 2

user7389132
user7389132

Reputation: 305

When you get the Eggs.data try:

JSON.parse(JSON.stringify(Eggs.data))

makes a deep copy of the array

Upvotes: 0

Related Questions