MCPcopy Index your code
hub / github.com/reactjs/react-codemod / inlineGetInitialState

Function inlineGetInitialState

transforms/class.js:494–550  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

492
493
494 const inlineGetInitialState = getInitialState => {
495 const functionExpressionCollection = j(getInitialState.value);
496
497 // at this point if there exists bindings like `const props = ...`, we
498 // already know the RHS must be `this.props` (see `isGetInitialStateConstructorSafe`)
499 // so it's safe to just remove them
500 functionExpressionCollection.find(j.VariableDeclarator, {id: {name: 'props'}})
501 .forEach(path => j(path).remove());
502
503 functionExpressionCollection.find(j.VariableDeclarator, {id: {name: 'context'}})
504 .forEach(path => j(path).remove());
505
506 return functionExpressionCollection
507 .find(j.ReturnStatement)
508 .filter(path => {
509 // filter out inner function declarations here (helper functions, promises, etc.).
510 const mainBodyCollection = j(getInitialState.value.body);
511 return (
512 mainBodyCollection
513 .find(j.ArrowFunctionExpression)
514 .find(j.ReturnStatement, path.value)
515 .size() === 0 &&
516 mainBodyCollection
517 .find(j.FunctionDeclaration)
518 .find(j.ReturnStatement, path.value)
519 .size() === 0 &&
520 mainBodyCollection
521 .find(j.FunctionExpression)
522 .find(j.ReturnStatement, path.value)
523 .size() === 0
524 );
525 })
526 .forEach(path => {
527 let shouldInsertReturnAfterAssignment = false;
528
529 // if the return statement is not a direct child of getInitialState's body
530 if (getInitialState.value.body.body.indexOf(path.value) === -1) {
531 shouldInsertReturnAfterAssignment = true;
532 }
533
534 j(path).replaceWith(j.expressionStatement(
535 j.assignmentExpression(
536 '=',
537 j.memberExpression(
538 j.thisExpression(),
539 j.identifier('state'),
540 false
541 ),
542 path.value.argument
543 )
544 ));
545
546 if (shouldInsertReturnAfterAssignment) {
547 j(path).insertAfter(j.returnStatement(null));
548 }
549 }).getAST()[0].value.body.body;
550 };
551

Callers 1

createConstructorFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected