React testing library how to use waitFor - javascript

I'm following a tutorial on React testing. The tutorial has a simple component like this, to show how to test asynchronous actions:
import React from 'react'
const TestAsync = () => {
const [counter, setCounter] = React.useState(0)
const delayCount = () => (
setTimeout(() => {
setCounter(counter + 1)
}, 500)
)
return (
<>
<h1 data-testid="counter">{ counter }</h1>
<button data-testid="button-up" onClick={delayCount}> Up</button>
<button data-testid="button-down" onClick={() => setCounter(counter - 1)}>Down</button>
</>
)
}
export default TestAsync
And the test file is like this:
import React from 'react';
import { render, cleanup, fireEvent, waitForElement } from '#testing-library/react';
import TestAsync from './TestAsync'
afterEach(cleanup);
it('increments counter after 0.5s', async () => {
const { getByTestId, getByText } = render(<TestAsync />);
fireEvent.click(getByTestId('button-up'))
const counter = await waitForElement(() => getByText('1'))
expect(counter).toHaveTextContent('1')
});
The terminal says waitForElement has been deprecated and to use waitFor instead.
How can I use waitFor in this test file?

If you're waiting for appearance, you can use it like this:
it('increments counter after 0.5s', async() => {
const { getByTestId, getByText } = render(<TestAsync />);
fireEvent.click(getByTestId('button-up'));
await waitFor(() => {
expect(getByText('1')).toBeInTheDocument();
});
});
Checking .toHaveTextContent('1') is a bit "weird" when you use getByText('1') to grab that element, so I replaced it with .toBeInTheDocument().

Would it be also possible to wrap the assertion using the act
function? Based on the docs I don't understand in which case to use
act and in which case to use waitFor.
The answer is yes. You could write this instead using act():
import { act } from "react-dom/test-utils";
it('increments counter after 0.5s', async() => {
const { getByTestId, getByText } = render(<TestAsync />);
// you wanna use act() when there is a render to happen in
// the DOM and some change will take place:
act(() => {
fireEvent.click(getByTestId('button-up'));
});
expect(getByText('1')).toBeInTheDocument();
});
Hope this helps.

Current best practice would be to use findByText in that case. This function is a wrapper around act, and will query for the specified element until some timeout is reached.
In your case, you can use it like this:
it('increments counter after 0.5s', async () => {
const { findByTestId, findByText } = render(<TestAsync />);
fireEvent.click(await findByTestId('button-up'))
const counter = await findByText('1')
});
You don't need to call expect on its value, if the element doesn't exist it will throw an exception
You can find more differences about the types of queries here

Related

Debouncing with multiple hooks

I am trying to implement debouncing in my app, however, the most I am able to achieve is to debounce the speed of the input. The gist of the App, is that it first takes input from the user, to generate a list of cities, according to the input and when selected, will provide a forecast for the whole week.
Here is the original code, without debouncing:
import React, { useState, useEffect } from 'react';
import * as Style from './Searchbar.styles';
import { weatherAPI } from '../API/api';
import endpoints from '../Utils/endpoints';
import { minCharacters } from '../Utils/minChars';
import MultiWeather from './MultiCard';
import useDebounce from '../Hooks/useDebounce';
export default function SearchBar() {
const [cityName, setCityName] = useState('');
const [results, setResults] = useState([]);
const [chooseCityForecast, setChooseCityForecast] = useState([]);
useEffect(() => {
if (cityName.length > minCharacters) {
loadCities();
}
}, [cityName, loadCities]);
//this is used to handle the input from the user
const cityValueHandler = value => {
setCityName(value);
};
//first API call to get list of cities according to user input
const loadCities = async () => {
try {
const res = await weatherAPI.get(endpoints.GET_CITY(cityName));
setResults(res.data.locations);
} catch (error) {
alert(error);
}
};
//second API call to get the forecast
const getCurrentCity = async city => {
try {
const res = await weatherAPI.get(endpoints.GET_DAILY_BY_ID(city.id));
console.log(res);
setChooseCityForecast(res.data.forecast);
setCityName('');
setResults([]);
} catch (error) {
alert(error);
}
};
return (
<Style.Container>
<h1>Search by City</h1>
<Style.Search>
<Style.SearchInner>
<Style.Input type="text" value={cityName} onChange={e => cityValueHandler(e.target.value)} />
</Style.SearchInner>
<Style.Dropdown>
{cityName.length > minCharacters ? (
<Style.DropdownRow results={results}>
{results.map(result => (
<div key={result.id}>
<span
onClick={() => getCurrentCity(result)}
>{`${result.name}, ${result.country}`}</span>
</div>
))}
</Style.DropdownRow>
) : null}
</Style.Dropdown>
</Style.Search>
{chooseCityForecast && (
<section>
<MultiWeather data={chooseCityForecast} />
</section>
)}
</Style.Container>
);
}
The code above works perfectly, aside from creating an API call everytime I add an additional letter. I have refered to this thread on implementing debouncing. When adjusted to my code, the implementation looks like this:
const debounce = (fn, delay) => {
let timerId;
return (...args) => {
clearTimeout(timerId);
timerId = setTimeout(() => fn(...args), delay);
}
};
const debouncedHandler = useCallback(debounce(cityValueHandler, 200), []);
But, as mentioned before, this results in debouncing/delaying user input by 200ms, while still creating additional API calls which each extra letter.
If I try to debounce the loadCities function or add a setTimeout method, it will delay the function, but will still make the API calls with each additional letter.
I have a hunch, that I need to remake the logic, which is handling the input, but at this point I am out of ideas.
After some digging I found a simple solution, that will be refactored later, but the gist of it is to move the loadCities function inside the use effect and implenet useTimeout and clearTimeout methods within the useEffect and wrapping the API call function, as seen below:
useEffect(() => {
let timerID;
if (inputValue.length > minCharacters) {
timerID = setTimeout(async () => {
try {
const res = await weatherAPI.get(endpoints.GET_CITY(inputValue));
setResults(res.data.locations);
} catch (error) {
alert(error);
}
}, 900);
}
return () => {
clearTimeout(timerID);
};
}, [inputValue]);
Hope this will help someone.

waitFor unable to find HTML element after setTimeout and advanceTimersByTime

I have a component that utilises quite a few setTimeouts in order to do three things: a) mount a child to the DOM, b) animate that child in, c) unmount that child after user interaction.
I'm trying to mock this behaviour in a test, and am specifically testing step b - I'm doing a queryByText to grab the text value of the child that I animate in.
However, the text never seems to show up in the HTML that gets printed to the CLI when the test fails. The error is as follows:
expect(received).toBeInTheDocument()
received value must be an HTMLElement or an SVGElement.
Received has value: null
My test looks like this:
it("should show message after setTimeout", async () => {
jest.useFakeTimers();
jest.advanceTimersByTime(5000);
const amendedMockContext = {
...baseMockContext,
introductionData: {
data: {
cta: "This is a cta!",
},
},
};
customRender(<FAB />, { contextProps: amendedMockContext });
const message = screen.queryByText(/this/i);
await waitFor(() => expect(message).toBeInTheDocument());
});
and my component animates in and out like so. Note the $visible flag triggers the animation:
const CTA_REVEAL_TIME = 5000;
export default function FAB() {
const [showCTA, setShowCTA] = useState(false);
const [mountCTA, setMountCTA] = useState(false);
// mount just before animating (step a)
useEffect(() => {
const mountCTATimer = setTimeout(
() => setMountCTA(true),
CTA_REVEAL_TIME - 1000
);
return () => {
clearTimeout(mountCTATimer);
};
}, []);
// animate in message (step b)
useEffect(() => {
const CTATimer = setTimeout(
() => setShowCTA((prevState) => !prevState),
CTA_REVEAL_TIME
);
return () => {
clearTimeout(CTATimer);
};
}, []);
return (
<>
{mountCta && <p $visible={showCTA}>{message}</p>}
</>
);
}
In my test, I've tried using various methods of async/await, waitFor, all the different query/get/find methods, but can't seem to get it to actually await the message revealing, even though I'm artificially advaning time by 5000ms. I also use advanceTimersBytime in other tests and have no such problems.
You should mount the component first, then advance the timers.
import { act, render, screen, waitFor } from '#testing-library/react';
import '#testing-library/jest-dom';
import React from 'react';
import FAB from './FAB';
describe('71867883', () => {
it('should show message after setTimeout', async () => {
jest.useFakeTimers();
render(<FAB />);
act(() => {
jest.advanceTimersByTime(5000);
})
await waitFor(() => expect(screen.queryByText(/this/i)).toBeInTheDocument());
});
});

Not able to figure out this error: Can't perform a React state update on an unmounted component [duplicate]

Problem
I am writing an application in React and was unable to avoid a super common pitfall, which is calling setState(...) after componentWillUnmount(...).
I looked very carefully at my code and tried to put some guarding clauses in place, but the problem persisted and I am still observing the warning.
Therefore, I've got two questions:
How do I figure out from the stack trace, which particular component and event handler or lifecycle hook is responsible for the rule violation?
Well, how to fix the problem itself, because my code was written with this pitfall in mind and is already trying to prevent it, but some underlying component's still generating the warning.
Browser console
Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount
method.
in TextLayerInternal (created by Context.Consumer)
in TextLayer (created by PageInternal) index.js:1446
d/console[e]
index.js:1446
warningWithoutStack
react-dom.development.js:520
warnAboutUpdateOnUnmounted
react-dom.development.js:18238
scheduleWork
react-dom.development.js:19684
enqueueSetState
react-dom.development.js:12936
./node_modules/react/cjs/react.development.js/Component.prototype.setState
react.development.js:356
_callee$
TextLayer.js:97
tryCatch
runtime.js:63
invoke
runtime.js:282
defineIteratorMethods/</prototype[method]
runtime.js:116
asyncGeneratorStep
asyncToGenerator.js:3
_throw
asyncToGenerator.js:29
Code
Book.tsx
import { throttle } from 'lodash';
import * as React from 'react';
import { AutoWidthPdf } from '../shared/AutoWidthPdf';
import BookCommandPanel from '../shared/BookCommandPanel';
import BookTextPath from '../static/pdf/sde.pdf';
import './Book.css';
const DEFAULT_WIDTH = 140;
class Book extends React.Component {
setDivSizeThrottleable: () => void;
pdfWrapper: HTMLDivElement | null = null;
isComponentMounted: boolean = false;
state = {
hidden: true,
pdfWidth: DEFAULT_WIDTH,
};
constructor(props: any) {
super(props);
this.setDivSizeThrottleable = throttle(
() => {
if (this.isComponentMounted) {
this.setState({
pdfWidth: this.pdfWrapper!.getBoundingClientRect().width - 5,
});
}
},
500,
);
}
componentDidMount = () => {
this.isComponentMounted = true;
this.setDivSizeThrottleable();
window.addEventListener("resize", this.setDivSizeThrottleable);
};
componentWillUnmount = () => {
this.isComponentMounted = false;
window.removeEventListener("resize", this.setDivSizeThrottleable);
};
render = () => (
<div className="Book">
{ this.state.hidden && <div className="Book__LoadNotification centered">Book is being loaded...</div> }
<div className={this.getPdfContentContainerClassName()}>
<BookCommandPanel
bookTextPath={BookTextPath}
/>
<div className="Book__PdfContent" ref={ref => this.pdfWrapper = ref}>
<AutoWidthPdf
file={BookTextPath}
width={this.state.pdfWidth}
onLoadSuccess={(_: any) => this.onDocumentComplete()}
/>
</div>
<BookCommandPanel
bookTextPath={BookTextPath}
/>
</div>
</div>
);
getPdfContentContainerClassName = () => this.state.hidden ? 'hidden' : '';
onDocumentComplete = () => {
try {
this.setState({ hidden: false });
this.setDivSizeThrottleable();
} catch (caughtError) {
console.warn({ caughtError });
}
};
}
export default Book;
AutoWidthPdf.tsx
import * as React from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
interface IProps {
file: string;
width: number;
onLoadSuccess: (pdf: any) => void;
}
export class AutoWidthPdf extends React.Component<IProps> {
render = () => (
<Document
file={this.props.file}
onLoadSuccess={(_: any) => this.props.onLoadSuccess(_)}
>
<Page
pageNumber={1}
width={this.props.width}
/>
</Document>
);
}
Update 1: Cancel throttleable function (still no luck)
const DEFAULT_WIDTH = 140;
class Book extends React.Component {
setDivSizeThrottleable: ((() => void) & Cancelable) | undefined;
pdfWrapper: HTMLDivElement | null = null;
state = {
hidden: true,
pdfWidth: DEFAULT_WIDTH,
};
componentDidMount = () => {
this.setDivSizeThrottleable = throttle(
() => {
this.setState({
pdfWidth: this.pdfWrapper!.getBoundingClientRect().width - 5,
});
},
500,
);
this.setDivSizeThrottleable();
window.addEventListener("resize", this.setDivSizeThrottleable);
};
componentWillUnmount = () => {
window.removeEventListener("resize", this.setDivSizeThrottleable!);
this.setDivSizeThrottleable!.cancel();
this.setDivSizeThrottleable = undefined;
};
render = () => (
<div className="Book">
{ this.state.hidden && <div className="Book__LoadNotification centered">Book is being loaded...</div> }
<div className={this.getPdfContentContainerClassName()}>
<BookCommandPanel
BookTextPath={BookTextPath}
/>
<div className="Book__PdfContent" ref={ref => this.pdfWrapper = ref}>
<AutoWidthPdf
file={BookTextPath}
width={this.state.pdfWidth}
onLoadSuccess={(_: any) => this.onDocumentComplete()}
/>
</div>
<BookCommandPanel
BookTextPath={BookTextPath}
/>
</div>
</div>
);
getPdfContentContainerClassName = () => this.state.hidden ? 'hidden' : '';
onDocumentComplete = () => {
try {
this.setState({ hidden: false });
this.setDivSizeThrottleable!();
} catch (caughtError) {
console.warn({ caughtError });
}
};
}
export default Book;
Here is a React Hooks specific solution for
Error
Warning: Can't perform a React state update on an unmounted component.
Solution
You can declare let isMounted = true inside useEffect, which will be changed in the cleanup callback, as soon as the component is unmounted. Before state updates, you now check this variable conditionally:
useEffect(() => {
let isMounted = true; // note mutable flag
someAsyncOperation().then(data => {
if (isMounted) setState(data); // add conditional check
})
return () => { isMounted = false }; // cleanup toggles value, if unmounted
}, []); // adjust dependencies to your needs
const Parent = () => {
const [mounted, setMounted] = useState(true);
return (
<div>
Parent:
<button onClick={() => setMounted(!mounted)}>
{mounted ? "Unmount" : "Mount"} Child
</button>
{mounted && <Child />}
<p>
Unmount Child, while it is still loading. It won't set state later on,
so no error is triggered.
</p>
</div>
);
};
const Child = () => {
const [state, setState] = useState("loading (4 sec)...");
useEffect(() => {
let isMounted = true;
fetchData();
return () => {
isMounted = false;
};
// simulate some Web API fetching
function fetchData() {
setTimeout(() => {
// drop "if (isMounted)" to trigger error again
// (take IDE, doesn't work with stack snippet)
if (isMounted) setState("data fetched")
else console.log("aborted setState on unmounted component")
}, 4000);
}
}, []);
return <div>Child: {state}</div>;
};
ReactDOM.render(<Parent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<div id="root"></div>
<script>var { useReducer, useEffect, useState, useRef } = React</script>
Extension: Custom useAsync Hook
We can encapsulate all the boilerplate into a custom Hook, that automatically aborts async functions in case the component unmounts or dependency values have changed before:
function useAsync(asyncFn, onSuccess) {
useEffect(() => {
let isActive = true;
asyncFn().then(data => {
if (isActive) onSuccess(data);
});
return () => { isActive = false };
}, [asyncFn, onSuccess]);
}
// custom Hook for automatic abortion on unmount or dependency change
// You might add onFailure for promise errors as well.
function useAsync(asyncFn, onSuccess) {
useEffect(() => {
let isActive = true;
asyncFn().then(data => {
if (isActive) onSuccess(data)
else console.log("aborted setState on unmounted component")
});
return () => {
isActive = false;
};
}, [asyncFn, onSuccess]);
}
const Child = () => {
const [state, setState] = useState("loading (4 sec)...");
useAsync(simulateFetchData, setState);
return <div>Child: {state}</div>;
};
const Parent = () => {
const [mounted, setMounted] = useState(true);
return (
<div>
Parent:
<button onClick={() => setMounted(!mounted)}>
{mounted ? "Unmount" : "Mount"} Child
</button>
{mounted && <Child />}
<p>
Unmount Child, while it is still loading. It won't set state later on,
so no error is triggered.
</p>
</div>
);
};
const simulateFetchData = () => new Promise(
resolve => setTimeout(() => resolve("data fetched"), 4000));
ReactDOM.render(<Parent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<div id="root"></div>
<script>var { useReducer, useEffect, useState, useRef } = React</script>
More on effect cleanups: Overreacted: A Complete Guide to useEffect
To remove - Can't perform a React state update on an unmounted component warning, use componentDidMount method under a condition and make false that condition on componentWillUnmount method. For example : -
class Home extends Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
news: [],
};
}
componentDidMount() {
this._isMounted = true;
ajaxVar
.get('https://domain')
.then(result => {
if (this._isMounted) {
this.setState({
news: result.data.hits,
});
}
});
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
...
}
}
If above solutions dont work, try this and it works for me:
componentWillUnmount() {
// fix Warning: Can't perform a React state update on an unmounted component
this.setState = (state,callback)=>{
return;
};
}
There is a hook that's fairly common called useIsMounted that solves this problem (for functional components)...
import { useRef, useEffect } from 'react';
export function useIsMounted() {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => isMounted.current = false;
}, []);
return isMounted;
}
then in your functional component
function Book() {
const isMounted = useIsMounted();
...
useEffect(() => {
asyncOperation().then(data => {
if (isMounted.current) { setState(data); }
})
});
...
}
Checking if a component is mounted is actually an anti pattern as per React documentation. The solution to the setState warning is rather to leverage on the use of an AbortController:
useEffect(() => {
const abortController = new AbortController() // creating an AbortController
fetch(url, { signal: abortController.signal }) // passing the signal to the query
.then(data => {
setState(data) // if everything went well, set the state
})
.catch(error => {
if (error.name === 'AbortError') return // if the query has been aborted, do nothing
throw error
})
return () => {
abortController.abort() // stop the query by aborting on the AbortController on unmount
}
}, [])
For asynchronous operations that aren't based on the Fetch API, there still should be a way to cancel these asynchronous operations, and you should rather leverage these than just checking if a component is mounted. If you are building your own API, you can implement the AbortController API in it to handle it.
For more context, the check if a component is mounted is an anti pattern as React is checking internally if the component is mounted to display that warning. Doing the same check again is just a way to hide the warning, and there are some easier ways to hide them than adding this piece of code on a big part of a codebase.
Source: https://medium.com/doctolib/react-stop-checking-if-your-component-is-mounted-3bb2568a4934
I had this warning possibly because of calling setState from an effect hook (This is discussed in these 3 issues linked together).
Anyway, upgrading the react version removed the warning.
React already removed this warning
but here is a better solution (not just workaround)
useEffect(() => {
const abortController = new AbortController() // creating an AbortController
fetch(url, { signal: abortController.signal }) // passing the signal to the query
.then(data => {
setState(data) // if everything went well, set the state
})
.catch(error => {
if (error.name === 'AbortError') return // if the query has been aborted, do nothing
throw error
})
return () => {
abortController.abort()
}
}, [])
The solution from #ford04 didn't worked to me and specially if you need to use the isMounted in multiple places (multiple useEffect for instance), it's recommended to useRef, as bellow:
Essential packages
"dependencies":
{
"react": "17.0.1",
}
"devDependencies": {
"typescript": "4.1.5",
}
My Hook Component
export const SubscriptionsView: React.FC = () => {
const [data, setData] = useState<Subscription[]>();
const isMounted = React.useRef(true);
React.useEffect(() => {
if (isMounted.current) {
// fetch data
// setData (fetch result)
return () => {
isMounted.current = false;
};
}
}
});
try changing setDivSizeThrottleable to
this.setDivSizeThrottleable = throttle(
() => {
if (this.isComponentMounted) {
this.setState({
pdfWidth: this.pdfWrapper!.getBoundingClientRect().width - 5,
});
}
},
500,
{ leading: false, trailing: true }
);
I know that you're not using history, but in my case I was using the useHistory hook from React Router DOM, which unmounts the component before the state is persisted in my React Context Provider.
To fix this problem I have used the hook withRouter nesting the component, in my case export default withRouter(Login), and inside the component const Login = props => { ...; props.history.push("/dashboard"); .... I have also removed the other props.history.push from the component, e.g, if(authorization.token) return props.history.push('/dashboard') because this causes a loop, because the authorization state.
An alternative to push a new item to history.
Add a ref to a jsx component and then check it exist
function Book() {
const ref = useRef();
useEffect(() => {
asyncOperation().then(data => {
if (ref.current) setState(data);
})
});
return <div ref={ref}>content</div>
}
I had a similar issue thanks #ford04 helped me out.
However, another error occurred.
NB. I am using ReactJS hooks
ndex.js:1 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
What causes the error?
import {useHistory} from 'react-router-dom'
const History = useHistory()
if (true) {
history.push('/new-route');
}
return (
<>
<render component />
</>
)
This could not work because despite you are redirecting to new page all state and props are being manipulated on the dom or simply rendering to the previous page did not stop.
What solution I found
import {Redirect} from 'react-router-dom'
if (true) {
return <redirect to="/new-route" />
}
return (
<>
<render component />
</>
)
If you are fetching data from axios and the error still occurs, just wrap the setter inside the condition
let isRendered = useRef(false);
useEffect(() => {
isRendered = true;
axios
.get("/sample/api")
.then(res => {
if (isRendered) {
setState(res.data);
}
return null;
})
.catch(err => console.log(err));
return () => {
isRendered = false;
};
}, []);
I have 2 solutions for this error:
return:
If you are used hook and useEffect, So put a return end of useEffect.
useEffect(() => {
window.addEventListener('mousemove', logMouseMove)
return () => {
window.removeEventListener('mousemove', logMouseMove)
}
}, [])
componentWillUnmount:
If you are used componentDidMount, So put componentWillUnmount next to it.
componentDidMount() {
window.addEventListener('mousemove', this.logMouseMove)
}
componentWillUnmount() {
window.removeEventListener('mousemove', this.logMouseMove)
}
The isMounted approach is an anti-pattern in most cases because it doesn't actually clean up/cancel anything, it just avoids changing state on unmounted components, but does nothing with pending asynchronous tasks. The React team recently removed the leak warning because users keep creating a lot of anti-patterns to hide the warning rather than fix its cause.
But writing cancellable code in plain JS can be really tricky. To fix this I made my own lib useAsyncEffect2 with custom hooks, built on top of a cancellable promise (c-promise2) for executing cancellable async code to reach its graceful cancellation. All async stages (promises), including deep ones, are cancellable. This means that the request here will be automatically aborted if its parent context is canceled. Of course, any other asynchronous operation can be used instead of a request.
useAsyncEffect Demo with plain useState usage (Live Demo):
import React, { useState } from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpAxios from "cp-axios";
function TestComponent({url}) {
const [text, setText] = useState("");
const cancel = useAsyncEffect(
function* () {
setText("fetching...");
const json = (yield cpAxios(url)).data;
setText(`Success: ${JSON.stringify(json)}`);
},
[url]
);
return (
<div>
<div>{text}</div>
<button onClick={cancel}>
Cancel request
</button>
</div>
);
}
useAsyncEffect Demo with internal states usage (Live Demo):
import React from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpAxios from "cp-axios";
function TestComponent({ url, timeout }) {
const [cancel, done, result, err] = useAsyncEffect(
function* () {
return (yield cpAxios(url).timeout(timeout)).data;
},
{ states: true, deps: [url] }
);
return (
<div>
{done ? (err ? err.toString() : JSON.stringify(result)) : "loading..."}
<button onClick={cancel} disabled={done}>
Cancel async effect (abort request)
</button>
</div>
);
}
Class component using decorators (Live demo)
import React, { Component } from "react";
import { ReactComponent } from "c-promise2";
import cpAxios from "cp-axios";
#ReactComponent
class TestComponent extends Component {
state = {
text: ""
};
*componentDidMount(scope) {
const { url, timeout } = this.props;
const response = yield cpAxios(url).timeout(timeout);
this.setState({ text: JSON.stringify(response.data, null, 2) });
}
render() {
return (<div>{this.state.text}</div>);
}
}
export default TestComponent;
More other examples:
Axios request with errors handling
Fetch weather by coords
Live search
Pause & Resume
Progress capturing
Edit: I just realized the warning is referencing a component called TextLayerInternal. That's likely where your bug is. The rest of this is still relevant, but it might not fix your problem.
1) Getting the instance of a component for this warning is tough. It looks like there is some discussion to improve this in React but there currently is no easy way to do it. The reason it hasn't been built yet, I suspect, is likely because components are expected to be written in such a way that setState after unmount isn't possible no matter what the state of the component is. The problem, as far as the React team is concerned, is always in the Component code and not the Component instance, which is why you get the Component Type name.
That answer might be unsatisfactory, but I think I can fix your problem.
2) Lodashes throttled function has a cancel method. Call cancel in componentWillUnmount and ditch the isComponentMounted. Canceling is more "idiomatically" React than introducing a new property.
UPDATE DO NOT USE MY ORIGINAL ANSWER AS IT DOES NOT WORK
This answer was based on the use of cancelable promises and a note in makecancelable which I migrated to use hooks. However, it appears it does not cancel a chain of async/await and even cancelable-promise does not support canceling of a chain of awaits
Doing a bit more research on this, it appears that some internal Google reasons prevented cancelable promises from coming into the standard.
Further more, there was some promise with Bluebird which introduces cancelable promises, but it does not work in Expo or at least I haven't seen an example of it working in Expo.
The accepted answer is the best. Since I use TypeScript I had adapted the code with a few modifications (I explicitly set the dependencies since the accepted answer's implicit dependencies appear to give a re-render loop on my app, added and use async/await rather than promise chain, pass a ref to the mounted object so that an async/await chain can be canceled earlier if needed)
/**
* This starts an async function and executes another function that performs
* React state changes if the component is still mounted after the async
* operation completes
* #template T
* #param {(mountedRef: React.MutableRefObject<boolean>) => Promise<T>} asyncFunction async function,
* it has a copy of the mounted ref so an await chain can be canceled earlier.
* #param {(asyncResult: T) => void} onSuccess this gets executed after async
* function is resolved and the component is still mounted
* #param {import("react").DependencyList} deps
*/
export function useAsyncSetEffect(asyncFunction, onSuccess, deps) {
const mountedRef = useRef(false);
useEffect(() => {
mountedRef.current = true;
(async () => {
const x = await asyncFunction(mountedRef);
if (mountedRef.current) {
onSuccess(x);
}
})();
return () => {
mountedRef.current = false;
};
}, deps);
}
Original answer
Since I have many different operations that are async, I use the cancelable-promise package to resolve this issue with minimal code changes.
Previous code:
useEffect(() =>
(async () => {
const bar = await fooAsync();
setSomeState(bar);
})(),
[]
);
New code:
import { cancelable } from "cancelable-promise";
...
useEffect(
() => {
const cancelablePromise = cancelable(async () => {
const bar = await fooAsync();
setSomeState(bar);
})
return () => cancelablePromise.cancel();
},
[]
);
You can alsowrpte it in a custom utility function like this
/**
* This wraps an async function in a cancelable promise
* #param {() => PromiseLike<void>} asyncFunction
* #param {React.DependencyList} deps
*/
export function useCancelableEffect(asyncFunction, deps) {
useEffect(() => {
const cancelablePromise = cancelable(asyncFunction());
return () => cancelablePromise.cancel();
}, deps);
}
In my case of a login-like screen, the fetch was done in a onClick handler of a parent component, who passed that handler down to the child, whom placed .catch and .finally on it.
In the .then case a redirect (and hence unmount) would happen as normal operation, and only in cases of fetch error would the child stay mounted on-screen.
My solution was moving the setState and all other code from the .finally to the .catch since the child is guaranteed to be mounted in the .catch case. And in the .then case nothing needed doing because of the guaranteed unmount.
Based on #ford04 answer, here is the same encapsulated in a method :
import React, { FC, useState, useEffect, DependencyList } from 'react';
export function useEffectAsync( effectAsyncFun : ( isMounted: () => boolean ) => unknown, deps?: DependencyList ) {
useEffect( () => {
let isMounted = true;
const _unused = effectAsyncFun( () => isMounted );
return () => { isMounted = false; };
}, deps );
}
Usage:
const MyComponent : FC<{}> = (props) => {
const [ asyncProp , setAsyncProp ] = useState( '' ) ;
useEffectAsync( async ( isMounted ) =>
{
const someAsyncProp = await ... ;
if ( isMounted() )
setAsyncProp( someAsyncProp ) ;
});
return <div> ... ;
} ;
Depending on how you open your webpage, you may not be causing a mounting. Such as using a <Link/> back to a page that was already mounted in the virtual DOM, so requiring data from a componentDidMount lifecycle is caught.
Here is a simple solution for this. This warning is due to when we do some fetch request while that request is in the background (because some requests take some time.)and we navigate back from that screen then they react cannot update the state. here is the example code for this. write this line before every state Update.
if(!isScreenMounted.current) return;
Here is the Complete Code
import React , {useRef} from 'react'
import { Text,StatusBar,SafeAreaView,ScrollView, StyleSheet } from 'react-native'
import BASEURL from '../constants/BaseURL';
const SearchScreen = () => {
const isScreenMounted = useRef(true)
useEffect(() => {
return () => isScreenMounted.current = false
},[])
const ConvertFileSubmit = () => {
if(!isScreenMounted.current) return;
setUpLoading(true)
var formdata = new FormData();
var file = {
uri: `file://${route.params.selectedfiles[0].uri}`,
type:`${route.params.selectedfiles[0].minetype}`,
name:`${route.params.selectedfiles[0].displayname}`,
};
formdata.append("file",file);
fetch(`${BASEURL}/UploadFile`, {
method: 'POST',
body: formdata,
redirect: 'manual'
}).then(response => response.json())
.then(result => {
if(!isScreenMounted.current) return;
setUpLoading(false)
}).catch(error => {
console.log('error', error)
});
}
return(
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<Text>Search Screen</Text>
</ScrollView>
</SafeAreaView>
</>
)
}
export default SearchScreen;
const styles = StyleSheet.create({
scrollView: {
backgroundColor:"red",
},
container:{
flex:1,
justifyContent:"center",
alignItems:"center"
}
})
I solved this problem by providing all the params that are used in the useEffect hook
The code reported the bug:
useEffect(() => {
getDistrict({
geonameid: countryId,
subdistrict: level,
}).then((res) => {
......
});
}, [countryId]);
The code after fix:
useEffect(() => {
getDistrict({
geonameid: countryId,
subdistrict: level,
}).then((res) => {
......
});
}, [countryId,level]);
Can see that , problems solved after I provided all the params(including the level param) that supposed to pass through.
I had a similar problem and solved it :
I was automatically making the user logged-in by dispatching an action on redux
( placing authentication token on redux state )
and then I was trying to show a message with this.setState({succ_message: "...")
in my component.
Component was looking empty with the same error on console : "unmounted component".."memory leak" etc.
After I read Walter's answer up in this thread
I've noticed that in the Routing table of my application ,
my component's route wasn't valid if user is logged-in :
{!this.props.user.token &&
<div>
<Route path="/register/:type" exact component={MyComp} />
</div>
}
I made the Route visible whether the token exists or not.
In my case the issue was that the parent component was hidding the child because of a condition change in the child component.
So what I did was to change the condition so the child component was always shown.
What was happening:
const ParentComponent:FC = () => {
...
if (someCondition) {
return null;
}
return (
<>
Some cool text here
<ChildModalComponent message="this is a cool modal" />
</>
)
}
const ChildModalComponent: FC = () => {
...
const handleSubmit = () => {
setSomeCondition(true);
}
}
So after clicking submit the modal was automatically hidden becasue of the parent condition (someCondition).
How did I fix it?
I changed the place where the someCondition was checked in the Parent component, so the child component was always shown:
const ParentComponent:FC = () => {
...
return (
<>
{!someCondition && <>Some cool text here</>
<ChildModalComponent message="this is a cool modal" />
</>
)
}
I faced same warning, not it is fixed. To fix the issue, I removed the useRef() variable check in useEffect()
Earlier, the code was
const varRef = useRef();
useEffect(() => {
if (!varRef.current)
{
}
}, []);
Now, the code is
const varRef = useRef();
useEffect(() => {
//if (!varRef.current)
{
}
}, [])
Hope, it helps...
Inspired by the accepted answer by #ford04 I had even better approach dealing with it, instead of using useEffect inside useAsync create a new function that returns a callback for componentWillUnmount :
function asyncRequest(asyncRequest, onSuccess, onError, onComplete) {
let isMounted=true
asyncRequest().then((data => isMounted ? onSuccess(data):null)).catch(onError).finally(onComplete)
return () => {isMounted=false}
}
...
useEffect(()=>{
return asyncRequest(()=>someAsyncTask(arg), response=> {
setSomeState(response)
},onError, onComplete)
},[])
const handleClick = async (item: NavheadersType, index: number) => {
const newNavHeaders = [...navheaders];
if (item.url) {
await router.push(item.url); =>>>> line causing error (causing route to happen)
// router.push(item.url); =>>> coreect line
newNavHeaders.forEach((item) => (item.active = false));
newNavHeaders[index].active = true;
setnavheaders([...newNavHeaders]);
}
};
The simplest and most compact solution (with an explanation) is seen below as a one-liner solution.
useEffect(() => { return () => {}; }, []);
The useEffect() example above returns a callback function triggers React to finish its unmount portion of its life-cycle prior to updating state.
That very simplistic solution is all that is needed. In addition, it also works unlike the fictional syntax provided by #ford04 and #sfletche . By the way, the below code snippet from #ford04 is purely imaginary syntax (#sfletche , #vinod , #guneetgstar , and #Drew Cordano used the very same imaginary syntax).
data => {       <--- Fictional/Imaginary Syntax
someAsyncOperation().then(data => {
if (isMounted) setState(data); // add conditional check
})
All of my linters and all the linters of my entire team will not accept it and they report Uncaught SyntaxError: unexpected token: '=>'. I am surprised that no one caught the imaginary syntax. Would anyone who has participated in this question-thread, particularly among the up-voters, explain to me how they got the solutions to work for them?
Inspired by #ford04 answer I use this hook, which also takes callbacks for success, errors, finally and an abortFn:
export const useAsync = (
asyncFn,
onSuccess = false,
onError = false,
onFinally = false,
abortFn = false
) => {
useEffect(() => {
let isMounted = true;
const run = async () => {
try{
let data = await asyncFn()
if (isMounted && onSuccess) onSuccess(data)
} catch(error) {
if (isMounted && onError) onSuccess(error)
} finally {
if (isMounted && onFinally) onFinally()
}
}
run()
return () => {
if(abortFn) abortFn()
isMounted = false
};
}, [asyncFn, onSuccess])
}
If the asyncFn is doing some kind of fetch from back-end it often makes sense to abort it when the component is unmounted (not always though, sometimes if ie. you're loading some data into a store you might as well just want to finish it even if component is unmounted)

React Unit Testing State Updates

I'm in the middle of trying to get as close to 100% unit test coverage with my React application as possible, however I'm in a bit of a pickle with trying to get test coverage on the useAsync hook. I took the following code from use react hooks:
import { useState, useEffect, useCallback } from 'react';
const useAsync = (asyncFunction, immediate = true) => {
const [status, setStatus] = useState('idle');
const [value, setValue] = useState(null);
const [error, setError] = useState(null);
// The execute function wraps asyncFunction and
// handles setting state for pending, value, and error.
// useCallback ensures the below useEffect is not called
// on every render, but only if asyncFunction changes.
const execute = useCallback(() => {
setStatus('pending');
setValue(null);
setError(null);
return asyncFunction()
.then(response => {
setValue(response);
setStatus('success');
})
.catch(error => {
setError(error);
setStatus('error');
});
}, [asyncFunction]);
// Call execute if we want to fire it right away.
// Otherwise execute can be called later, such as
// in an onClick handler.
useEffect(() => {
if (immediate) {
execute();
}
}, [execute, immediate]);
return { execute, status, value, error };
};
And it works fine. I've not done anything funky or included any additional testing libraries/dependencies on top of what you'd get when you run npx create-react-app ....
Because I couldn't find a suitable solution for my team to test react hooks without relying on additional dependencies, i.e. react-hooks-testing-library, I created a mock component to wrap the hook in, then I just test the different possible states like so:
import React from "react";
import { render, cleanup } from "#testing-library/react";
import { useAsync } from "../../hooks";
afterEach(cleanup);
const MockComponent = (props) => {
const { status } = useAsync(props.callback, props.immediate);
return <p id="test">{status}</p>
};
const defaultCallback = () => {
new Promise((resolve) => {
setTimeout(() => {
resolve("Success!");
}, 1000)
});
};
// Example of a test that runs fine, no problem at all!
test("useAsync gets to a pending state", () => {
const { container } = render(<MockComponent callback={defaultCallback} immediate={true} />
const pTag = container.querySelector("p#test");
expect(pTag.textContent).toBe("idle");
});
// This is where I get my issue...
test("useAsync gets to a success state", (done) => {
const { container } = render(<MockComponent callback={defaultCallback} immediate={true} />
const pTag = container.querySelector("p#test");
setTimeout(() => {
expect(pTag.textContent).toBe("success");
done();
}, 2000);
});
// Some other tests...
When I run these two tests that I've included above, they actually run fine and if I look at the code coverage report(s) that are generated, it's 100% coverage. In the console, though, when running these tests, when I run the second one, I get the following error and I'm not sure how to resolve it. I have tried to wrap the entire body of the test in act, but that made no difference, so I'm not entirely sure what the best approach may be here.
Here's the console output:
console.error
Warning: An update to MockComponent inside a tests was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
at MockComponent....
As I've said, I've tried to wrap my entire test(s) with an act, but I've had no luck there. What I have found interesting is that in the console output, when it apparently errors, it also highlights this snippet of the hook:
.then(response => {
setValue(response);
// ^
setStatus('success');
// ^
})
.catch(error => {
setError(error);
Should I perhaps ignore this issue? After all when all of my tests are run, no tests/test suite fails or anything.
Okay, so after much tinkering & googling, I found an answer to my problem, thankfully it's relatively straightforward! 😃 - The short answer being the use of waitFor.
I made a couple of other modifications, i.e. assigned the timeout delay to a variable called timeout, but nothing major.
import React from "react";
import { render, cleanup, waitFor } from "#testing-library/react";
import { useAsync } from "../../hooks";
afterEach(cleanup);
let timeout = 1000;
beforeEach(() => {
timeout = 1000
});
const MockComponent = (props) => {
const { status } = useAsync(props.callback, props.immediate);
return <p id="test">{status}</p>
};
const defaultCallback = () => {
new Promise((resolve) => {
setTimeout(() => {
resolve("Success!");
}, timeout)
});
};
// Example of a test that runs fine, no problem at all!
test("useAsync gets to a pending state", () => {
const { container } = render(<MockComponent callback={defaultCallback} immediate={true} />
const pTag = container.querySelector("p#test");
expect(pTag.textContent).toBe("idle");
});
// This now works! :D
test("useAsync gets to a success state", async () => {
timeout = 0;
const { container } = render(<MockComponent callback={defaultCallback} immediate={true} />
const pTag = container.querySelector("p#test");
expect(pTag).toBeInTheDocument();
// Yes!
await waitFor(() => {
expect(pTag.textContent).toBe("success");
});
});
// Some other tests...

Testing asynchronous useEffect

My functional component uses the useEffect hook to fetch data from an API on mount. I want to be able to test that the fetched data is displayed correctly.
While this works fine in the browser, the tests are failing because the hook is asynchronous the component doesn't update in time.
Live code:
https://codesandbox.io/s/peaceful-knuth-q24ih?fontsize=14
App.js
import React from "react";
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve(4), 400);
});
}
function App() {
const [members, setMembers] = React.useState(0);
React.useEffect(() => {
async function fetch() {
const response = await getData();
setMembers(response);
}
fetch();
}, []);
return <div>{members} members</div>;
}
export default App;
App.test.js
import App from "./App";
import React from "react";
import { mount } from "enzyme";
describe("app", () => {
it("should render", () => {
const wrapper = mount(<App />);
console.log(wrapper.debug());
});
});
Besides that, Jest throws a warning saying:
Warning: An update to App inside a test was not wrapped in act(...).
I guess this is related? How could this be fixed?
Ok, so I think I've figured something out. I'm using the latest dependencies right now (enzyme 3.10.0, enzyme-adapter-react-16 1.15.1), and I've found something kind of amazing. Enzyme's mount() function appears to return a promise. I haven't seen anything about it in the documentation, but waiting for that promise to resolve appears to solve this problem. Using act from react-dom/test-utils is also essential, as it has all the new React magic to make the behavior work.
it('handles async useEffect', async () => {
const component = mount(<MyComponent />);
await act(async () => {
await Promise.resolve(component);
await new Promise(resolve => setImmediate(resolve));
component.update();
});
console.log(component.debug());
});
Following on from #user2223059's answer it also looks like you can do:
// eslint-disable-next-line require-await
component = await mount(<MyComponent />);
component.update();
Unfortunately you need the eslint-disable-next-line because otherwise it warns about an unnecessary await... yet removing the await results in incorrect behaviour.
I was having this problem and came across this thread. I'm unit testing a hook but the principles should be the same if your async useEffect code is in a component. Because I'm testing a hook, I'm calling renderHook from react hooks testing library. If you're testing a regular component, you'd call render from react-dom, as per the docs.
The problem
Say you have a react hook or component that does some async work on mount and you want to test it. It might look a bit like this:
const useMyExampleHook = id => {
const [someState, setSomeState] = useState({});
useEffect(() => {
const asyncOperation = async () => {
const result = await axios({
url: `https://myapi.com/${id}`,
method: "GET"
});
setSomeState(() => result.data);
}
asyncOperation();
}, [id])
return { someState }
}
Until now, I've been unit testing these hooks like this:
it("should call an api", async () => {
const data = {wibble: "wobble"};
axios.mockImplementationOnce(() => Promise.resolve({ data}));
const { result } = renderHook(() => useMyExampleHook());
await new Promise(setImmediate);
expect(result.current.someState).toMatchObject(data);
});
and using await new Promise(setImmediate); to "flush" the promises. This works OK for simple tests like my one above but seems to cause some sort of race condition in the test renderer when we start doing multiple updates to the hook/component in one test.
The answer
The answer is to use act() properly. The docs say
When writing [unit tests]... react-dom/test-utils provides a helper called act() that makes sure all updates related to these “units” have been processed and applied to the DOM before you make any assertions.
So our simple test code actually wants to look like this:
it("should call an api on render and store the result", async () => {
const data = { wibble: "wobble" };
axios.mockImplementationOnce(() => Promise.resolve({ data }));
let renderResult = {};
await act(async () => {
renderResult = renderHook(() => useMyExampleHook());
})
expect(renderResult.result.current.someState).toMatchObject(data);
});
The crucial difference is that async act around the initial render of the hook. That makes sure that the useEffect hook has done its business before we start trying to inspect the state. If we need to update the hook, that action gets wrapped in its own act block too.
A more complex test case might look like this:
it('should do a new call when id changes', async () => {
const data1 = { wibble: "wobble" };
const data2 = { wibble: "warble" };
axios.mockImplementationOnce(() => Promise.resolve({ data: data1 }))
.mockImplementationOnce(() => Promise.resolve({ data: data2 }));
let renderResult = {};
await act(async () => {
renderResult = renderHook((id) => useMyExampleHook(id), {
initialProps: { id: "id1" }
});
})
expect(renderResult.result.current.someState).toMatchObject(data1);
await act(async () => {
renderResult.rerender({ id: "id2" })
})
expect(renderResult.result.current.someState).toMatchObject(data2);
})
I was also facing similar issue. To solve this I have used waitFor function of React testing library in enzyme test.
import { waitFor } from '#testing-library/react';
it('render component', async () => {
const wrapper = mount(<Component {...props} />);
await waitFor(() => {
wrapper.update();
expect(wrapper.find('.some-class')).toHaveLength(1);
}
});
This solution will wait for our expect condition to fulfill. Inside expect condition you can assert on any HTML element which get rendered after the api call success.
this is a life saver
export const waitForComponentToPaint = async (wrapper: any) => {
await act(async () => {
await new Promise(resolve => setTimeout(resolve, 0));
await wait(0);
wrapper.update();
});
};
in test
await waitForComponentToPaint(wrapper);
After lots of experimentation I have come up with a solution that finally works for me, and hopefully will fit your purpose.
See below
import React from "react";
import { mount } from "enzyme";
import { act } from 'react-dom/test-utils';
import App from "./App";
describe("app", () => {
it("should render", async () => {
const wrapper = mount(<App />);
await new Promise((resolve) => setImmediate(resolve));
await act(
() =>
new Promise((resolve) => {
resolve();
})
);
wrapper.update();
// data loaded
});
});

Categories

Resources