Home > front end >  Error handling multiple map array in single view
Error handling multiple map array in single view

Time:09-30

I have two Select input to display data. lets say 1 Select is for product and other for display product list based on selected product in select 1. But i had an error that react didnt display my view. after i command the second Select it is run normally.

this is my Select input to select product and coverage:

<div>
<Select onChange={handleChangeSelect} value={TocId} name="ProductID" size="sm">
  {TOC.map((type, index) => (
           <Select.Option key={type.id} value={type.id}>
                 {type.desc}
           </Select.Option>
        ))}
</Select>
<Select onChange={handleChangeSelect} value={TocId} name="ProductID" size="sm">
  {Coverage.map((type, index) => (
           <Select.Option key={type.id} value={type.id}>
                 {type.desc}
           </Select.Option>
        ))}
</Select>
</div>

i get the coverage data by hit the api, after select product using hooks state Like this:

const getCoverage = () => {
    axios.post( url, data, headers).then(function (response){
    if(response.data.Data == 'success') {
    setCoverage(response.data.Data)
}
})
}

const handleChangeSelect = (e) => {
        setTocId(e);
        console.log(TocId);
        getCoverage();
    };

CodePudding user response:

Hard to tell without seeing the rest of your code but are you fetching Coverage for the first time in handleChangeSelect?

If so, that would be the issue since Coverage doesn't exist in your first render.

A potential workaround could be to make the Coverage options render conditionally.

<div>
<Select onChange={handleChangeSelect} value={TocId} name="ProductID" size="sm">
  {TOC.map((type, index) => (
           <Select.Option key={type.id} value={type.id}>
                 {type.desc}
           </Select.Option>
        ))}
</Select>
<Select onChange={handleChangeSelect} value={TocId} name="ProductID" size="sm">
  {Coverage && Coverage.length > 0 && Coverage.map((type, index) => (
           <Select.Option key={type.id} value={type.id}>
                 {type.desc}
           </Select.Option>
        ))}
</Select>
</div>

CodePudding user response:

It looks fine. As per my perception, it's an issue of empty state rendering. Render your component conditionally. Also, put a different name prop.

<div>
<Select
    onChange={handleChangeSelect}
    value={TocId}
    name="ProductID"
    size="sm"
>
    {TOC?.map((type, index) => (
        <Select.Option key={type.id} value={type.id}>
            {type.desc}
        </Select.Option>
    ))}
</Select>
<Select
    onChange={handleChangeSelect}
    value={TocId}
    name="ProductID"
    size="sm"
>
    {Coverage?.map((type, index) => (
        <Select.Option key={type.id} value={type.id}>
            {type.desc}
        </Select.Option>
    ))}
</Select>
  • Related