JedWatson / react-select

The Select Component for React.js
https://react-select.com/
MIT License
27.63k stars 4.13k forks source link

React select loadOptions is not getting called in 2nd render #3920

Open sujoys10 opened 4 years ago

sujoys10 commented 4 years ago

I have two async form field. Based on the selection of first field, 2nd field fetches data through loadOptions function. I observed that the with input change in the first field, the loadOptions of 2nd filed is not re-executing. How fix this issue?

`import React, { useState, useEffect } from 'react' import { useHistory } from 'react-router-dom' import { useApolloClient} from 'react-apollo'; import { Formik, Form, ErrorMessage } from 'formik'; import * as Yup from "yup"; import AsyncSelect from 'react-select/async' import AsyncPaginate from 'react-select-async-paginate' import { GET_ITEM_CODES, GET_ITEMCODE_SPECIFICATIONS } from '../../library/Query';

export default function SampleForm({initialData}){
const history = useHistory();

const [productFilter, setProductFilter] = useState('');

const client = useApolloClient();

const defaultAdditional = {
    cursor : null
}
const shouldLoadMore = (scrollHeight, clientHeight, scrollTop) => {
    const bottomBorder = (scrollHeight - clientHeight) / 2
     return bottomBorder < scrollTop
}
const loadItemcodeOptions = async (q = 0, prevOptions, {cursor}) => {
    console.log('qu',q*1)
    const options = [];
    console.log('load')
    const response = await client.query({
        query:GET_ITEM_CODES,
        variables : {filter: {
            number_gte : q*1
        },skip:0, first:4, after: cursor}
    })

    console.log('res',response)
    response.data.itemCodes.itemCodes.map(item => {
        return options.push({
            value: item.number,
            label: `${item.number} ${item.description}`
        })
    })
    console.log('0',options)

    return {
        options,
        hasMore: response.data.itemCodes.hasMore,
        additional: {
            cursor: response.data.itemCodes.cursor.toString()
        }
    }
}

const loadProductOptions = async (productFilter) => {
    console.log('x', productFilter)
    if(!!productFilter){
        console.log('if',!productFilter)
        const response = await client.query({
            query: GET_ITEMCODE_SPECIFICATIONS,
            variables: { filter: {
                itemCode: productFilter
            }}
        })

        console.log('respo',response.data)

        const options = [];
        response.data.itemCodeSpecifications.map(item => {
            return options.push({
                value: item.product,
                label: `${item.product}`
            })
        })
        console.log(options) 
        return options
    }else {
        console.log('else')
        return []
    }
}

const handleFilter = (e) => {
    console.log('e',e)
    setProductFilter(e.value)
    console.log('pf',productFilter)
}

useEffect(() => {
    console.log('epf',productFilter)
})
console.log('rpf',productFilter)
return(
    <Formik
       initialValues = {{
           itemCode: !!initialData ? {value: initialData.itemCode, label: initialData.itemCode} : '',
       }}

       validationSchema = {Yup.object().shape({
           itemCode: Yup.number().required('Required'),
       })}
    >
        {({values, isSubmitting, setFieldValue, touched, errors }) => (
            <Form>
                <label htmlFor="itemCode">Item Code</label>
                <AsyncPaginate
                    name="itemCode"
                    defaultOptions
                    debounceTimeout={300}
                    cacheOptions
                    additional={defaultAdditional}
                    value={values.itemCode}
                    loadOptions={loadItemcodeOptions}
                    onChange={option => {
                        handleFilter(option)
                        setFieldValue('itemCode', option)
                    }}
                    shouldLoadMore={shouldLoadMore}
                />
                <ErrorMessage name="itemcode"/>
                <div>rerender{productFilter}</div>
                <AsyncSelect
                    name="product"
                    isDisabled={!productFilter} 
                    cacheOptions
                    defaultOptions
                    value={values.product}
                    loadOptions={loadProductOptions}
                    onChange={option => setFieldValue('product', option)}
                />
                <pre>{JSON.stringify(values, null, 2)}</pre>
            </Form>
        )}

    </Formik>
)

}`

efriandika commented 4 years ago

Hi @bladey

I got similar problem when I was using "async" and "await" in my loadOptions function

onSelectChange = _.debounce(async (inputValue, callback) => {
     const response = await axios.get('/users');
     callback(response.data);
}, 800)

When I changed to Promises axios, it works as expected:

onSelectChange = _.debounce((inputValue, callback) => {
    axios.get('/users').then(response => {
       calback(response.data);
   })
}, 800)
bladey commented 4 years ago

Thanks for the further information @efriandika

khurram-wasim commented 3 years ago

In reference to this you can stringify your options whenever they update, and assign that string as a key to AsyncSelect. This causes a re-render.