John
John

Reputation: 93

react useState() not changing the value(an object) in the first render

I am using react usestate() and I want to update device state(It is an object)

my problem is when ShowRelays component renders for the first time device is an empty object and It does not get updated during first rendering, but for the next renders everything is fine

How can I update device state for the first time rendering?

(sorry for my bad english)

.

function ShowRelays(props) {

const [device, setDevice] = useState({})

let reduxDevices = useSelector(state => state.devicesReducer.devices)

let findDevice = () => {
    let myDevice = reduxDevices.find(x => x._id === props.id)
    setDevice(prevState => {
        return {
            ...prevState,
            ...myDevice
        }
    })
   
}


useEffect(() => {
    if (props.show) {
        findDevice()
    }
}, [props.show])


return
  (
   <div>
    test
   </div>
  )
}

myDevice object is like:

{active: true, name: "device1", id: "deviceId"}

Upvotes: 0

Views: 363

Answers (1)

Ogod
Ogod

Reputation: 948

You can pass a function to your useState-hook which will calculate your initial value for device.

see lazy init state

function ShowRelays(props) {
    let reduxDevices = useSelector(state => state.devicesReducer.devices);
    const [device, setDevice] = useState(() => {
        return reduxDevices.find(x => x._id === props.id)
    });

    return <div>test</div>;
}

An other possible solution for your problem without using a separate state could be the following (directly select the right device from your selector function):

function ShowRelays(props) {
    const device = useSelector(state => {
        return state.devicesReducer.devices.find(x => x._id === props.id);
    });
    return <div>test</div>;
}

Upvotes: 2

Related Questions