Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert State to useState hook in React Native?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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."
}

>Solution :

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}));
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading