Consider the following example that renders a list of iframes.
I'd like to store all the documents of the rendered iframes in frames.
import React, { useState, useEffect, useCallback } from "react";
import Frame, { FrameContextConsumer } from "react-frame-component";
function MyFrame({ id, document, setDocument }) {
useEffect(() => {
console.log(`Setting the document for ${id}`);
setDocument(id, document);
}, [id, document]); // Caution: Adding `setDocument` to the array causes an infinite update loop!
return <h1>{id}</h1>;
}
export default function App() {
const [frames, setFrames] = useState({
desktop: {
name: "Desktop"
},
mobile: {
name: "Mobile"
}
});
const setFrameDocument = useCallback(
(id, document) => {
setFrames({
...frames,
[id]: {
...frames[id],
document
}
});
},
[frames, setFrames]
);
console.log(frames);
return (
<div className="App">
{Object.keys(frames).map(id => (
<Frame key={id}>
<FrameContextConsumer>
{({ document }) => (
<MyFrame
id={id}
document={document}
setDocument={setFrameDocument}
/>
)}
</FrameContextConsumer>
</Frame>
))}
</div>
);
}
There are two issues here:
react-hooks/exhaustive-depsis complaining thatsetDocumentis missing in the dependency array. But, adding it causing an infinite update loop.- Console logging
framesshows that only mobile'sdocumentwas set. I expect desktop'sdocumentto be set as well.
How would you fix this?