Hello I try to duplicate a view by press on a "draggable item". I've got it working on a "components function". But when I use Hooks it not works, it gives me an error:
"Too many re-renders. React limits the number of renders to prevent an infinite loop."
This is the view who I try add:
const addNewPLayer = () => {
return (
<Draggable
x={240}
y={300}
renderSize={20}
renderColor="red"
renderText="u"
/>
);
};
This is my add function:
const [newplayer, setNewPlayer] = useState([]);
const addPlayer = () => {
setNewPlayer([...newplayer, <addNewPLayer />]);
};
This my "button", onShortPressRelease works like onPress.
<Draggable
key={key}
x={"80%"}
y={50}
renderColor="blue"
renderSize={50}
isCircle
renderText={item.name}
onShortPressRelease={addPlayer()}
/>
And to display this view a just added my state
{newplayer}
What doing I'am wrong?
I can not test everything with what you sent, but the first thing that strikes me is the <Draggable />
component.
In its props onShortPressRelease
you instantaneously call the addPlayer
function, I do believe what you want would be either
<Draggable
...
onShortPressRelease={addPlayer}
/>
or
<Draggable
...
onShortPressRelease={() => addPlayer()}
so that it adds a player only when you actually release the key.
This is important because if Draggable
is rendered with everything else, it would call setPlayer
function, triggering a new render, re-rendering Draggable
, which would again rerender... thus resulting in an infinite render loop.