Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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
/>

>Solution :

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

Edit competent-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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading