This is a migrated thread and some comments may be shown as answers.

DropDownList Default value from Async Source

2 Answers 259 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Robert
Top achievements
Rank 1
Robert asked on 15 Jul 2019, 06:07 PM

Hi Stefan, 

I am struggling with this currently. I simply want to default the dropdownlist based on an async data load. I am running a GraphQL query when the component renders, and wish to default the DropDownList to any item in that resulting data array that matches the route parameter passed in (if any).

I cannot find any examples showcasing this.

2 Answers, 1 is accepted

Sort by
0
Robert
Top achievements
Rank 1
answered on 15 Jul 2019, 06:30 PM

For some reason, this took me way longer than it should have.

This is how I managed to get it working...dunno if this is the best approach or not.

const AdminRates = withRouter(({ history, ...props }) => {
 
    const { match: { params: { id = null } } } = props;
 
    const [defaultRate, setDefaultRate] = useState();
    const [rate, setRate] = useState();
    const { data: { rates = [] }, error, loading } = useQuery(RATES_QUERY);
 
 
    // handle the async rates defaulting
    useEffect(() => {
        setDefaultRate(
            rates.filter(rate => rate.id === id)[0]
        );
    }, [id, rates]);
 
 
    const handleRateChange = (e) => {
        setRate(e.target.value);
    };
 
    return (
        <DropDownList
            data={rates}
            textField="name"
            dataItemKey="id"
            defaultValue={defaultRate}
            value={rate}
            onChange={handleRateChange}
        />
    );
});
0
Stefan
Telerik team
answered on 16 Jul 2019, 12:23 PM
Hello, Robert,

This seems as a valid approach as it monitors for changes in the rates collection and the id value.

This will lets know when the request is completed and we have the new values.

It is indeed looking as the best approach to cover this case.


Regards,
Stefan
Progress Telerik
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Tags
General Discussions
Asked by
Robert
Top achievements
Rank 1
Answers by
Robert
Top achievements
Rank 1
Stefan
Telerik team
Share this question
or