Improve async useEffect warning (#15104)
Dan Abramov committed
Mar 13, 2019 at 16:20 UTC
9d77a317bf5bde7e6edd3c8cd0ebb00feb447223
2 files changed
+14
-13
packages/react-reconciler/src/ReactFiberCommitWork.js
+11
-10
@@ -346,22 +346,23 @@ function commitHookEffectList(
346
} else if (typeof destroy.then === 'function') {
347
addendum =
348
'\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' +
349
- 'Instead, you may write an async function separately ' +
350
- 'and then call it from inside the effect:\n\n' +
351
- 'async function fetchComment(commentId) {\n' +
352
- ' // You can await here\n' +
353
- '}\n\n' +
349
+ 'Instead, write the async function inside your effect ' +
350
+ 'and call it immediately:\n\n' +
351
'useEffect(() => {\n' +
355
- ' fetchComment(commentId);\n' +
356
- '}, [commentId]);\n\n' +
357
- 'In the future, React will provide a more idiomatic solution for data fetching ' +
358
- "that doesn't involve writing effects manually.";
352
+ ' async function fetchData() {\n' +
353
+ ' // You can await here\n' +
354
+ ' const response = await MyAPI.getData(someId);\n' +
355
+ ' // ...\n' +
356
+ ' }\n' +
357
+ ' fetchData();\n' +
358
+ '}, [someId]);\n\n' +
359
+ 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';
360
} else {
361
addendum = ' You returned: ' + destroy;
362
}
363
warningWithoutStack(
364
false,
364
- 'An Effect function must not return anything besides a function, ' +
365
+ 'An effect function must not return anything besides a function, ' +
366
'which is used for clean-up.%s%s',
367
addendum,
368
getStackByFiberInDevAndProd(finishedWork),
packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js
+3
-3
@@ -715,20 +715,20 @@ describe('ReactHooks', () => {
715
716
const root1 = ReactTestRenderer.create(null);
717
expect(() => root1.update(<App return={17} />)).toWarnDev([
718
- 'Warning: An Effect function must not return anything besides a ' +
718
+ 'Warning: An effect function must not return anything besides a ' +
719
'function, which is used for clean-up. You returned: 17',
720
]);
721
722
const root2 = ReactTestRenderer.create(null);
723
expect(() => root2.update(<App return={null} />)).toWarnDev([
724
- 'Warning: An Effect function must not return anything besides a ' +
724
+ 'Warning: An effect function must not return anything besides a ' +
725
'function, which is used for clean-up. You returned null. If your ' +
726
'effect does not require clean up, return undefined (or nothing).',
727
]);
728
729
const root3 = ReactTestRenderer.create(null);
730
expect(() => root3.update(<App return={Promise.resolve()} />)).toWarnDev([
731
- 'Warning: An Effect function must not return anything besides a ' +
731
+ 'Warning: An effect function must not return anything besides a ' +
732
'function, which is used for clean-up.\n\n' +
733
'It looks like you wrote useEffect(async () => ...) or returned a Promise.',
734
]);