Skip to content

Commit 31cf281

Browse files
committed
feat(no-initialize-state): add arguments to message
#48
1 parent ff22dde commit 31cf281

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

src/rules/no-initialize-state.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export default {
2121
schema: [],
2222
messages: {
2323
avoidInitializingState:
24-
'Avoid initializing state in an effect. Instead, pass "{{state}}"\'s initial value to its `useState`. For SSR hydration, prefer `useSyncExternalStore`.',
24+
'Avoid initializing state in an effect. Instead, initialize "{{state}}"\'s `useState()` with "{{arguments}}". For SSR hydration, prefer `useSyncExternalStore()`.',
2525
},
2626
},
2727
create: (context) => ({
@@ -38,15 +38,19 @@ export default {
3838
.filter((ref) => isStateSetter(context, ref))
3939
.filter((ref) => isImmediateCall(ref.identifier))
4040
.forEach((ref) => {
41+
const callExpr = getCallExpr(ref);
4142
const useStateNode = getUseStateNode(context, ref);
4243
const stateName = (
4344
useStateNode.id.elements[0] ?? useStateNode.id.elements[1]
4445
)?.name;
46+
const argumentText = callExpr.arguments[0]
47+
? context.sourceCode.getText(callExpr.arguments[0])
48+
: "undefined";
4549

4650
context.report({
4751
node: getCallExpr(ref),
4852
messageId: "avoidInitializingState",
49-
data: { state: stateName },
53+
data: { state: stateName, arguments: argumentText },
5054
});
5155
});
5256
},

test/no-initialize-state.test.js

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ new MyRuleTester().run("no-initialize-state", rule, {
103103
errors: [
104104
{
105105
messageId: "avoidInitializingState",
106-
data: { state: "state" },
106+
data: { state: "state", arguments: '"Hello"' },
107107
},
108108
],
109109
},
@@ -122,7 +122,7 @@ new MyRuleTester().run("no-initialize-state", rule, {
122122
errors: [
123123
{
124124
messageId: "avoidInitializingState",
125-
data: { state: "state" },
125+
data: { state: "state", arguments: "otherState" },
126126
},
127127
],
128128
},
@@ -141,7 +141,25 @@ new MyRuleTester().run("no-initialize-state", rule, {
141141
errors: [
142142
{
143143
messageId: "avoidInitializingState",
144-
data: { state: "state" },
144+
data: { state: "state", arguments: "'Hello World'" },
145+
},
146+
],
147+
},
148+
{
149+
name: "To undefined",
150+
code: js`
151+
function MyComponent() {
152+
const [state, setState] = useState('Meow');
153+
154+
useEffect(() => {
155+
setState();
156+
}, []);
157+
}
158+
`,
159+
errors: [
160+
{
161+
messageId: "avoidInitializingState",
162+
data: { state: "state", arguments: "undefined" },
145163
},
146164
],
147165
},

0 commit comments

Comments
 (0)