Reputation: 17701
I am trying to set the state in request data method for a string variable like this below
const ViewChangeRequest = () => {
const [requestStageValue, setRequestStage] = useState('');
const { data: requestData, loading: requestDataLoading, error: requestDataError } =
useQuery(GET_SPECIFICREQUEST, {
variables: { requestinputs: { id } },
});
if (requestData != null) {
setRequestStage(requestData.allRequests[0].requestStage.name); // getting error at here
requestData.allRequests.map((code) => {
requestDatasource.push({
id: code.id,
section: code.masterSection.name,
createdBy: code.createdBy,
type: code.requestType.name,
status: code.requestStage.name,
createat: code.createdAt,
});
return null;
});
}
};
export default withRouter(ViewChangeRequest);
Depends upon the requeststage value, i am verifying conditions like this below
if (requestStageValue === 'Request Submitted') {
stepNumber = 0;
} else if (requestStageValue === 'In Review') {
stepNumber = 1;
} else {
stepNumber = 2;
}
I am getting an error Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
at this line setRequestStage(requestData.allRequests[0].requestStage.name)
I am not able to understand where i am doing wrong while setting up the state to string varaiable.
Could any one please help me out from this situation that would be very grateful to me, many thanks in advance.
Upvotes: 1
Views: 5210
Reputation: 9063
Well you're running setRequestStage
in the function. This will trigger a state update, which means the functions runs again (since state updates trigger re-renders), which means setRequestStage
runs again, which means the state updates again, so functions runs again etc. etc. - infinite loop.
If you're wanting to set an initial state based on requestData
, do it when declaring it in useState
:
const [requestStageValue, setRequestStage] = useState(
requestData !== null ? requestData.allRequests[0].requestStage.name : ''
);
Upvotes: 6