I converted a class component to function component. The issue is that I need to convert this.setState to useState hook. I'm trying to figure out how to change the following to the useState hook
state = {
services: {},
};
zeroconf.on('resolved', data => {
this.setState({
services: {
...this.state.services [data.host]: data,
},
});
}
I need to convert to useState hook but not sure how. Below is what I have tried
const [services, setServices] = useState({});
zeroconf.on('resolved', data => {
setServices(services:{...services [data.host]: data})
zeroconf.on('resolved', data) is a event listener and the information from data is:
{
"port": 51484,
"txt": {},
"addresses": [
"127.0.0.1",
"::1",
"fe80::1",
"192.168.0.10",
"fe80::46e"
],
"name": "printer",
"fullName": "Book-Pro.local._printer._tcp.",
"host": "Book-Pro.local."
}
CodePudding user response:
Just feed it the object, and take in the argument to get the most up to date value of services
.
const [services, setServices] = useState({});
zeroconf.on('resolved', data => {
setServices(currentServices => ({...currentServices, [data.host]: data}));
});