简体   繁体   中英

How to get ajax data in ReactJS

I am building ontop of a ReactJS embedable web ui script as I am new to ReactJS. Here I am trying to pull data from my server and trying to display in the web ui. The problem I am facing is with the data that is coming from server as I am unable to parse it. Please find the data format below:

0: Object { name: "{\"draw\":0,\"recordsTotal\":8,\"recordsFiltered\":8,\"data\":[{\"first_name\":\"John\",\"last_name\":\"taylor\"},
{\"first_name\":\"John1\",\"last_name\":\"taylor1\"}]}" }
​
1: Object { school: "{\"draw\":0,\"recordsTotal\":0,\"recordsFiltered\":0,\"data\":
[{\"name\":\"school1\",\"location\":\"location1\"},
{\"name\":\"school2\",\"location\":\"location2\"}]}" }

PS: I cannot change my server data format.

Model code (model.ts)

export interface NameModel {
    name: object;
}

Form code (form.tsx)

const Name = () => {
    const service = useContext(ServiceContext);
    const [name, setName] = useState<NameModel[] | undefined>(undefined);
    const [visible, setVisible] = useState(0);
    const [statusText, setStatusText] = useState('');

    const loaders = [useTimeout(() => !name && setStatusText('Loading...'), 500)];

    useEffect(() => {
        service?.getName()
            .then(setName)
            .catch(() => setStatusText('Failed to load, try again later.'))
            .then(() => loaders.forEach((c) => c()));
    }, [service]);

    return (
        <div>
            {
                !name
                    ? statusText
                    : <Fragment>
                        <ul className={style.root}>
                            {
                                name.map((q, i) => (
                                {q}
                                    ))
                            }
                        </ul>
                    </Fragment>
            }
        </div>
    );
};

The above code produces: Uncaught (in promise) TypeError: name.map is not a function

How do I display the first_name and last_name from the first object that is sent from my server?

Thanks

Your issue is that name can be undefined by default, causing the name.map((q... part of the code to error because undefined doesn't have a map function.

You can fix this by changing to a more sensible default of empty array:

const [name, setName] = useState<NameModel[]>([]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM