Skip to content

Instantly share code, notes, and snippets.

@azizhk
Created January 18, 2018 07:41
Show Gist options
  • Save azizhk/b4f9f5e45055a25bd28eef56540714e4 to your computer and use it in GitHub Desktop.
Save azizhk/b4f9f5e45055a25bd28eef56540714e4 to your computer and use it in GitHub Desktop.
Dispatch your reducer codemod

Codemod to convert your redux code from dispatching a type string to reducer function.

The reducer_codemod.js converts

export default createStore(initialState, {
  GOT_PAGE_DATA: (state, payload) => {
    return {
      ...state,
      data: payload
    };
  },
  GOT_PAGE2_DATA: (state, payload) => {
    return {
      ...state,
      data2: payload
    }
  }
})

to

export function GOT_PAGE_DATA (state, payload) {
  return {
    ...state,
    data: payload
  };
}

export function GOT_PAGE2_DATA (state, payload) {
  return {
    ...state,
    data2: payload
  };
}
// How to run:
// npm i -g jscodeshift
// jscodeshift -t codemods/reducer_codemod.js ./src/reducers/*.js
module.exports = function (fileInfo, api, options) {
const j = api.jscodeshift
// console.log(fileInfo)
const root = j(fileInfo.source)
return root
.find(j.ExportDefaultDeclaration, {
declaration: {
type: 'CallExpression',
callee: {
name: 'createReducer'
}
}
})
.replaceWith(p => {
const reducerObj = p.value.declaration.arguments[1]
if (reducerObj.type !== 'ObjectExpression') {
console.log("I can't do this")
return p
}
return reducerObj.properties.map(property => {
const key = property.key.name
if (
(property.value.type === 'FunctionExpression') ||
(property.value.type === 'ArrowFunctionExpression')
) {
const params = property.value.params
let body = property.value.body
if (body.type !== 'BlockStatement') {
body = j.blockStatement([j.returnStatement(body)])
}
return j.exportNamedDeclaration(
j.functionDeclaration(j.identifier(key), params, body)
)
} else if (property.value.type === 'Identifier') {
return j.exportNamedDeclaration(null, [
j.exportSpecifier(property.value, j.identifier(key))
])
}
})
})
.toSource()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment