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 can I reduce the useState("") duplication?

I’m working on an IP Adress tracker project, everything is working fine. My question is how can I reduce that useState("") to behave like it should? Should I set the useState as an object?

function App() {
  const [trakerData, setTrakerData] = useState({
    ipAddress: "",
    location: "",
    timezone: "",
    isp: "",
    latitude: "",
    longitude: "",
  });

  const url = `${BASE_URL}apiKey=${process.env.REACT_APP_API_KEY}&ipAddress=${ipAddress}`;

  useEffect(() => {
    const getData = async () => {
      axios.get(url).then((respone) => {
        setTrakerData({
          ...trakerData,
          ipAddress: respone.data.ip,
          location: respone.data.location.region,
          timezone: respone.data.location.timezone,
          isp: respone.data.isp,
          latitude: respone.data.location.lat,
          longitude: respone.data.location.lng,
        });
      });
    };

    getData();
  }, [url]);

  return (
    <div className="App">
      <SearchSection
        ipAddress={ipAddress}
        location={location}
        timezone={timezone}
        isp={isp}
        setIpAddress={setIpAddress}
      />
      <MapSection latitude={latitude} longitude={longitude} />
    </div>
  );
}

export default App;

>Solution :

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

Actually this also works fine, but if you want to look cleaner, you can set it as object like so :

const [trakerData, setTrakerData] = useState({  
   ipAddress: '',
   location: '',
   // the rest values

})

then you can update the state values

 const getData = async () => {
  axios.get(url).then((respone) => {
    setTrakerData({ 
          ...trakerData,
           ipAddress: respone.data.ip,
           // rest of the valeus
      })
  });
};

When you pass the props to SearchSection you have two options, to pass the entire state or values one by one

<SearchSection 
   // this options is good if you update the values inside the component
   trackerData={trackerData}
   setTrackerData={setTrackerData}
   // this option is read only
   ipAddress={trackerData.ipAddress}
/>
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