Skip to content

GraphQL: Update React code #570

@amotl

Description

@amotl

@coderabbitai recommended this:

⚠️ Potential issue

Improve error handling and update React rendering API.

Several improvements needed in the JavaScript implementation:

  1. ReactDOM.render is deprecated in React 18
  2. Fetch implementation lacks proper error handling
  3. Missing CSRF protection
  4. No request timeout handling

Apply these improvements:

       function graphQLFetcher(graphQLParams) {
-        return fetch('{{ endpoint }}', {
+        const controller = new AbortController();
+        const timeoutId = setTimeout(() => controller.abort(), 30000);
+        
+        return fetch('{{ endpoint }}', {
           method: 'post',
           headers: {
             'Accept': 'application/json',
             'Content-Type': 'application/json',
+            'X-CSRFToken': '{{ csrf_token }}',  // Add CSRF token
           },
           body: JSON.stringify(graphQLParams),
           credentials: 'include',
+          signal: controller.signal,
         }).then(function (response) {
+          if (!response.ok) {
+            throw new Error(`HTTP error! status: ${response.status}`);
+          }
           return response.text();
         }).then(function (responseBody) {
           try {
             return JSON.parse(responseBody);
           } catch (error) {
             return responseBody;
           }
+        }).catch(function (error) {
+          if (error.name === 'AbortError') {
+            throw new Error('Request timeout');
+          }
+          throw error;
+        }).finally(() => {
+          clearTimeout(timeoutId);
         });
       }

-      ReactDOM.render(
+      const root = ReactDOM.createRoot(document.getElementById('graphiql'));
+      root.render(
         React.createElement(GraphiQL, {
           fetcher: graphQLFetcher,
           query: parameters.query,
           variables: parameters.variables,
           operationName: parameters.operationName,
           onEditQuery: onEditQuery,
           onEditVariables: onEditVariables,
           onEditOperationName: onEditOperationName
-        }),
-        document.getElementById('graphiql')
+        })
       );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      function graphQLFetcher(graphQLParams) {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 30000);
        
        return fetch('{{ endpoint }}', {
          method: 'post',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token }}',  // Add CSRF token
          },
          body: JSON.stringify(graphQLParams),
          credentials: 'include',
          signal: controller.signal,
        }).then(function (response) {
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          return response.text();
        }).then(function (responseBody) {
          try {
            return JSON.parse(responseBody);
          } catch (error) {
            return responseBody;
          }
        }).catch(function (error) {
          if (error.name === 'AbortError') {
            throw new Error('Request timeout');
          }
          throw error;
        }).finally(() => {
          clearTimeout(timeoutId);
        });
      }

      const root = ReactDOM.createRoot(document.getElementById('graphiql'));
      root.render(
        React.createElement(GraphiQL, {
          fetcher: graphQLFetcher,
          query: parameters.query,
          variables: parameters.variables,
          operationName: parameters.operationName,
          onEditQuery: onEditQuery,
          onEditVariables: onEditVariables,
          onEditOperationName: onEditOperationName
        })
      );

Originally posted by @coderabbitai[bot] in #554 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions