Reputation: 463
Seems like this is a common issue in React, so apologies for asking this question again. I have a ParentComponent
that contains a map with state. The map needs to have state because you can update its contents are meant to be updated. When I try to set the state of the map, I get an error stating too many re-renders. I've even tried using the useEffect hook, but I can't figure out the issue. Here's what I have:
const ParentComponent = ({show, onCloseModalButton}) => {
const [resorts, setResorts] = React.useState(new Map())
const tmpResorts = new Map(resorts)
tmpResorts.set("Keystone", [39.6069742, -105.97011])
tmpResorts.set("Breckenridge", [39.4808, -106.0676])
tmpResorts.set("Vail", [39.6061, -106.3550])
tmpResorts.set("Crested Butte", [38.8991, -106.9658])
tmpResorts.set("Winter Park", [39.8841, -105.7627])
tmpResorts.set("Copper Mountain", [39.5022, -106.1497])
setResorts(tmpResorts)
...
Here's what I've tried, to no avail:
const ParentComponent = ({show, onCloseModalButton}) => {
const [resorts, setResorts] = React.useState(new Map())
const tmpResorts = new Map(resorts)
React.useEffect(() => {
tmpResorts.set("Keystone", [39.6069742, -105.97011])
tmpResorts.set("Breckenridge", [39.4808, -106.0676])
tmpResorts.set("Vail", [39.6061, -106.3550])
tmpResorts.set("Crested Butte", [38.8991, -106.9658])
tmpResorts.set("Winter Park", [39.8841, -105.7627])
tmpResorts.set("Copper Mountain", [39.5022, -106.1497])
setResorts(tmpResorts)
}, [tmpResorts])
...
Appreciate any help!
Upvotes: 0
Views: 51
Reputation: 265
Remove tmpResorts
from useEffect Dependency array will fix it:
const [resorts, setResorts] = useState(new Map());
useEffect(() => {
console.log('called');
const tmpResorts = new Map(resorts);
tmpResorts.set('Keystone', [39.6069742, -105.97011]);
tmpResorts.set('Breckenridge', [39.4808, -106.0676]);
tmpResorts.set('Vail', [39.6061, -106.355]);
tmpResorts.set('Crested Butte', [38.8991, -106.9658]);
tmpResorts.set('Winter Park', [39.8841, -105.7627]);
tmpResorts.set('Copper Mountain', [39.5022, -106.1497]);
setResorts(tmpResorts);
}, []);
Upvotes: 1