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 :
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}
/>