I've a stepper form, that insert data using GraphQL/Apollo and React, of two different places.
Here are the code:
export function ProjectStep({classes, nextStep}) {
const {loading, error, data} = useUserQuery();
const organizationsArray = _.get(data, "user.organizations");
const [projectName, setProjectName] = useState("");
const [organization, setOrganization] = useState("");
const [createProject, appMutationResponse] = useappInsertMutation();
const [createToken, tokenMutationResponse] = usetokenInsertMutation();
const submitForm = () => {
const variables = {name: projectName, orgId: organization, description: ""};
createProject({variables});
};
const submitToken = () => {
const variables = {
enable: true,
lastUsed: Date.now().toString(),
appId: appMutationResponse.data.appInsert.id,
orgId: appMutationResponse.data.appInsert.orgId,
};
createToken({variables});
};
if (appMutationResponse.data) {
submitToken();
}
}
The first insert is on:
const submitForm = () => {
const variables = {name: projectName, orgId: organization, description: ""};
createProject({variables});
};
The second insert is on:
const submitToken = () => {
const variables = {
enable: true,
lastUsed: Date.now().toString(),
appId: appMutationResponse.data.appInsert.id,
orgId: appMutationResponse.data.appInsert.orgId,
};
createToken({variables});
};
These events are called in a button:
<Button variant="contained" color="primary" type='button' onClick={submitForm}>
Next
</Button>
But, when i click on the button, i got this error:
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
When a go to my database, i see that 50 tokens are saved using this part of the code in a single call:
const submitToken = () => {
const variables = {
enable: true,
lastUsed: Date.now().toString(),
appId: appMutationResponse.data.appInsert.id,
orgId: appMutationResponse.data.appInsert.orgId,
};
createToken({variables});
};
I think that because i'm using a hook, i got a response and that response bring that error to me, the question is, why i'm saving and receiving in a single call, 50 tokens?
You have written below code directly in render, so when the appMutationResponse.data is available if calls the submitToken
function which triggers a re-render and then the function is called again causing an infinite loop.
if (appMutationResponse.data) {
submitToken();
}
The solution is to put this code in useEffect and run it on data change
useEffect(() => {
if (appMutationResponse.data) {
submitToken();
}
}, [appMutationResponse.data])