skip to Main Content

I am building my frontend using react app

I want when the user select a bank it will be added to the selectData state.

But it is not working as expected

when the user is selects a bank for the first time it does not add to the selectedData state but if the user select the second time it is added to the state

import React, { useState } from 'react'

export const terr = () => {
    const [selectedData, setSelectedData] = useState({})
    const onChange = (value) => {
        console.log(`selected ${value}`);

        setSelectedData({
            ...selectedData,
            "bank_code": value
        });
        console.log(`selected data ${selectedData}`);
    };
    return (
        <div>
            <Form.Item
                label="Bank Name"
                name="bank_code"
                rules={[
                    {
                        required: true,
                        message: 'Select your bank name!',
                    },
                ]}
            >
                <Select
                    showSearch
                    placeholder="Select a Bank"
                    optionFilterProp="children"
                    onChange={onChange}
                    onSearch={onSearch}
                    filterOption={filterOption}
                    options={banks}
                />
            </Form.Item>
        </div>
    )
}

2

Answers


  1. In React the setState function won’t update the state until the next render. To get it to update immediately you can use a callback in the setSelectedData function.

    setSelectedData(oldData => {
            ...oldData,
            "bank_code": value
        });
    
    Login or Signup to reply.
  2. Within onChange, the object that selectedData is bound to doesn’t change. Instead react will re-render the terr, and that will see the new object that you passed to setSelectedData, and you will have a new onChange that will close over it. As you note, a call to that onChange will see the modified selectedData.

    If you want to observe that object, give it a name before passing it to setSelectedData.

    const onChange = (value) => {
        console.log(`selected ${value}`);
    
        const data = {
            ...selectedData,
            "bank_code": value
        };
        setSelectedData(data);
        console.log(`selected data ${data}`);
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search