简体   繁体   中英

React.JS : make fetch to populate select

I'm trying to make a fetch to populate my select, but I can't use the fetch..

const loadOptions = async (searchQuery, loadedOptions, { page }) => {
    const requestMethod = {
                method: "PUT",
                headers: { 'Content-Type': 'application/json' },
                body: { realmIds: [props.realmScelto] }
            };
    
            const response = await fetch('myapi', requestMethod) // error is here, in requestMethod

            // const response = await axios.post(`myapi?page=${page}&size=20`, { realmIds: [props.realmScelto] }) // this works.. it gives me back 1 value, and it ok but add always the same value that I obtain from api

            // const optionToShow = await response.data
            const optionToShow = await response.json()
 return {
            options: optionToShow,
            hasMore: optionToShow.length >= 1,
            additional: {
                page: searchQuery ? 2 : page + 1,
            },
        };
    };

    const onChange = option => {
        if (typeof props.onChange === 'function') {
            props.onChange(option);
        }
    };

    return (
        <AsyncPaginate
            value={props.value}
            loadOptions={loadOptions}

            onChange={onChange}
            isSearchable={true}
            placeholder="Select"
            additional={{
                page: 0,
            }}
        />
    );

The error that I receive in the requestMethod is:

The argument of type '{method: string; headers: {'Content-Type': string; }; body: {realmIds: any []; }; } 'is not assignable to the parameter of type' RequestInit '. The types of the 'body' property are incompatible. The type '{realmIds: any []; } 'is not assignable to type' BodyInit '. In type '{realmIds: any []; } 'The following properties of type' URLSearchParams' are missing: append, delete, get, getAll and 4 more.

For fetch , the body you pass in is not converted to JSON automatically.

Try

const requestMethod = {
    method: "POST",
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ realmIds: [props.realmScelto] })
};
const response = await fetch(`myapi?page=${page}&size=20`, requestMethod)

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