简体   繁体   中英

How to set api json data to react-select default value

I want to set API JSON data to react-select default values

const [tag, setTag] = useState([])
const [tag_data, setTagData] = useState([[]]);

useEffect function for call API and get the JSON data

useEffect(() => {
        (async () => {
            const tag_result = await axios(`${process.env.REACT_APP_API_URL}/tag`);
            setTagData(tag_result.data);
        })();
    }, []);

Below is my API JSON data response

{id: 1, content_tag: 'Test'}
{id: 2, content_tag: 'test 1'}
{id: 3, content_tag: 'test 2'}
{id: 4, content_tag: 'test 3'}
<Select
    id="react-select-tag"
    isMulti
    options={tag_data}
    hideSelectedOptions={false}
    getOptionLabel={(option) => option.content_tag}
    getOptionValue={(option) => option.content_tag}
    // value={tag_data[0]}  This set the value but after that i am not able to change another tag
    // value={tag} This changed another tag but not set defaultvalue
    onChange={(e) => setTag(e)}
    defaultValue={tag_data[0]} //This changed another tag but not set defaultvalue
/>

You can update the state to set a default value after fetching the options:

编辑主管-lalande-hgs1g

const [tags, setTags] = useState([])
const [tagsData, setTagsData] = useState([]);

useEffect(() => {
        (async () => {
            const { data } = await axios(`${process.env.REACT_APP_API_URL}/tag`);
            setTagsData(data);
            setTags([data[0]]);
        })();
    }, []);

<Select
    id="react-select-tag"
    isMulti
    options={tagsData}
    hideSelectedOptions={false}
    getOptionLabel={(option) => option.content_tag}
    getOptionValue={(option) => option.id} // using id as it is unique
    value={tags}
    onChange={(selected) => setTags(selected)}
/>

I renamed a few variables

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