Cannot read property 'displayName' of undefined. React+Jest+Enzyme - reactjs

I am rendering a react Component App.tsx which uses useEffect hook. Inside the useEffect, it makes an async call updates the state delivery defined in App.tsx. At first render, delivery is undefined, but after next re-render, it is defined.
const App = () => {
const [delivery, setDelivery] = useState(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
setup()
}, [])
const setup = async () => {
try {
const response = await someAsyncCall()
setDelivery(response)
setLoading(true)
/// Other functionality
} catch (err) {
console.log(err)
}finally{
setLoading(false)
}
}
return (
<>
{loading? <div>Loading!!</div>
: <div>App has loaded with {delivery.displayName} {delivery.id}</div>
}
</>
)
}
How to write unit test so that it re-renders with right value? Right now I get Uncaught [TypeError: Cannot read property 'displayName' of undefined]
Unit Test I wrote :
describe('test', ()=>{
it("mounts", ()=>{
const wrapper = mount(<App />)
})
})
Any thoughts on how to re-render? I read wrapper.update() could be used. I was wondering how?

Shouldn't this solve the problem?
return (
<>
{loading || !delivery ? <div>Loading!!</div>
: <div>App has loaded with {delivery.displayName} {delivery.id}</div>
}
</>
)

Related

Initializing component with parameter from local storage in react/nextjs

I have a component provided by an external library which I need to provide an access token to. This access token is saved in localStorage at this point and I would like to read it and pass it to the component. This is my attempt using useEffect but this fails with the error {code: "initialization-error", error: "Access token required"}
const test: NextPage = () => {
const router = useRouter()
let accessToken = ''
useEffect(() => {
const at = localStorage.getItem('accessToken')
console.log(at) // prints out the correct access token
if (at !== null) {
accessToken = at
}
}, [])
return (
<WebSdk
accessToken={accessToken}
expirationHandler={() => Promise.resolve(accessToken)}
onError={(error) => {
console.log(error)
}}
/>
)
}
export default test
I'm guessing the useEffect hook runs after the component renderes - how can I read from local storage before or as the component renders?
Since you are using nextjs you can't call the localStorage directly, so you have to check if the bowser has "initialized", something like this:
const test: NextPage = () => {
const router = useRouter()
const [initialized, setInitialized] = useState(false);
const [accessToken, setAccessToken] = useState('');
useEffect(() => {
const at = localStorage.getItem('accessToken') || '';
setInitialized(true);
setAccessToken(at);
}, [])
if (!initialized) {
return null;
}
return (
<WebSdk
accessToken={accessToken}
expirationHandler={() => Promise.resolve(accessToken)}
onError={(error) => {
console.log(error)
}}
/>
)
}
export default test
I'm guessing the useEffect hook runs after the component renderes
Yes the component will render first before the hooks can be triggered, this is the equivalent of "componentDidMount" (if the hook's second parameter is empty) in early verions of react.

React+Jest Testing state change in useEffect

So I've a similar useCase defined in stackover flow answer, but somewhat different. I have a react component and it has two useEffect hooks. One useEffect hook is used at first time render and other once the dependency in that useEffect hook changes. I tried mocking getDelivery but it comes from a custom hook defined in app.
// App.tsx
const App = () => {
const [deliveryType, setDeliveryType] = useState([])
const { DeliveryStatusService } = useServices()
const deliveryStatusService = new DeliveryStatusService()
const { deliveryId } = useParams()
useEffect(() => {
setup()
}, [])
useEffect(() => {
if (deliveryType) {
console.log("DeliveryType is Set")
}
}, [deliveryType])
const setup = async () => {
const response = await deliveryStatusService.getDelivery(deliveryId) // this call comes from custom hook and external service
setDeliveryType(response)
}
return (
<>
<div>{!deliveryType ? <div>Render Loading</div> : <div>Data loaded with {deliveryType}</div>}</div>
</>
)
}
I tried to mock it out as stated in above article as follows using Jest and Enzyme but if I console.log(wrapper.debug) I still get Render Loading and not Data loaded with {deliveryType}.
I tried mocking it like this :
const getDelivery = jest.fn()
const DeliveryStatusService = jest.fn().mockImplementation(() => ({
getDelivery,
}))
it('mock getDelivery', () => {
const wrapper = mount(<ServiceProvider services={{DeliveryStatus}}>
<App />
</ServiceProvider>
getDelivery.mockReturnValue(
Promise.resolve(
... dummyData
),
)
await act(flushPromises)
wrapper.update()
await act(flushPromises)
console.log(wrapper.debug())
console.log(wrapper.debug()) yields the following output:
<ServiceProvider services={{...}}>
<App>
<div>
<div>
Render Loading
</div>
</div>
<App>
</ServiceProvider>
Am I not mocking correctly so that I would never have Data loaded div?

Getting a "Too many re-renders" error with React Hooks

I'm struggling with React Hooks here. I looked online, but couldn't figure out how to adapt the examples to my code. I have the following component which triggers a "Too many re-renders" error:
const EmailVerification = () => {
const [showMessage, setShowMessage] = useState(true);
const [text, setText] = useState("...Loading. Do not close.");
const { data, error } = useQuery(VERIFY_EMAIL);
if (error) {setText(genericErrorMessage);}
if (data) {setText(emailVerificationMessage);}
return (
<Wrapper>
<Message setShowMessage={setShowMessage} text={text} />
</Wrapper>
)
}
How can I reorganize my code to avoid this error? I know that the useEffect hook should be used to perform side effects, although I wouldn't know how to use it in this case (supposing it is necessary).
The error is triggered because you are using setText directly in the render function. This function renders the component after calling it. Because in the next render, data and error are still set, it calls setText again.
You are right about useEffect. With useEffect you can make sure that the setText function is only being called when a change occurs in the data. In your case, that is for the data and/or error variables.
import { useEffect } from 'react';
const EmailVerification = () => {
const [showMessage, setShowMessage] = useState(true);
const [text, setText] = useState("...Loading. Do not close.");
const { data, error } = useQuery(VERIFY_EMAIL);
useEffect(() => {
if (error) setText('message');
if (data) setText('emailVerificationMessage');
}, [error, data]);
return (
<Wrapper>
<Message setShowMessage={setShowMessage} text={text} />
</Wrapper>
)
}
However, since you are only changing the text variable using already existing props, you can also do this in JS(X) only:
const EmailVerification = () => {
const [showMessage, setShowMessage] = useState(true);
const { isLoading, data, error } = useQuery(VERIFY_EMAIL);
const text = isLoading ? 'Loading... Do not close' : error || !data ? 'Error message' : 'emailVerificationMessage';
return (
<Wrapper>
<Message setShowMessage={setShowMessage} text={text} />
</Wrapper>
)
}
This uses a nested ternary operator (not a fan) which can be replaced with any other method.
setText will cause a rerender and will be called again on the next render. As I understand, you want to set the text once the query returns either an error or the data.
To avoid this, either use onError and onCompleted that you can pass to useQuery like so :
const { data, error } = useQuery(VERIFY_EMAIL, {
onCompleted: () => setText(emailVerificationMessage),
onError: () => setText(genericErrorMessage)
});
and remove these two lines:
if (error) {setText(genericErrorMessage);}
if (data) {setText(emailVerificationMessage);}
or call setText in a useEffect:
useEffect(() => {
if (error) {
setText(genericErrorMessage)
}
}, [error])

React-hooks. Can't perform a React state update on an unmounted component

I get this error:
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 a useEffect cleanup
function.
when fetching of data is started and component was unmounted, but function is trying to update state of unmounted component.
What is the best way to solve this?
CodePen example.
default function Test() {
const [notSeenAmount, setNotSeenAmount] = useState(false)
useEffect(() => {
let timer = setInterval(updateNotSeenAmount, 2000)
return () => clearInterval(timer)
}, [])
async function updateNotSeenAmount() {
let data // here i fetch data
setNotSeenAmount(data) // here is problem. If component was unmounted, i get error.
}
async function anotherFunction() {
updateNotSeenAmount() //it can trigger update too
}
return <button onClick={updateNotSeenAmount}>Push me</button> //update can be triggered manually
}
The easiest solution is to use a local variable that keeps track of whether the component is mounted or not. This is a common pattern with the class based approach. Here is an example that implement it with hooks:
function Example() {
const [text, setText] = React.useState("waiting...");
React.useEffect(() => {
let isCancelled = false;
simulateSlowNetworkRequest().then(() => {
if (!isCancelled) {
setText("done!");
}
});
return () => {
isCancelled = true;
};
}, []);
return <h2>{text}</h2>;
}
Here is an alternative with useRef (see below). Note that with a list of dependencies this solution won't work. The value of the ref will stay true after the first render. In that case the first solution is more appropriate.
function Example() {
const isCancelled = React.useRef(false);
const [text, setText] = React.useState("waiting...");
React.useEffect(() => {
fetch();
return () => {
isCancelled.current = true;
};
}, []);
function fetch() {
simulateSlowNetworkRequest().then(() => {
if (!isCancelled.current) {
setText("done!");
}
});
}
return <h2>{text}</h2>;
}
You can find more information about this pattern inside this article. Here is an issue inside the React project on GitHub that showcase this solution.
If you are fetching data from axios(using hooks) 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;
};
}, []);
TL;DR
Here is a CodeSandBox example
The other answers work of course, I just wanted to share a solution I came up with.
I built this hook that works just like React's useState, but will only setState if the component is mounted. I find it more elegant because you don't have to mess arround with an isMounted variable in your component !
Installation :
npm install use-state-if-mounted
Usage :
const [count, setCount] = useStateIfMounted(0);
You can find more advanced documentation on the npm page of the hook.
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 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 Complete Example
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"
}
})
This answer is not related to the specific question but I got the same 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 a useEffect cleanup function. and as a React newcomer could not find a solution to it.
My problem was related to useState in an unmounted component.
I noticed that I was calling a set state function (setIsLoading) after the function that unmounted my component:
const Login = () => {
const [isLoading, setIsLoading] = useState(false);
const handleLogin = () => {
setIsLoading(true);
firebase.auth().then(
functionToUnMountLoginSection();
// the problem is here
setIsLoading(false);
)
}
}
The correct way is to call setIsLoading when the component is still mounted, before calling the function to unmount/process user login in my specific case:
firebase.auth().then(
setIsLoading(false);
functionToUnMountLoginSection();
)
You add the state related datas into the useEffect body for not rerunning them every rerendering process. This method will solve the problem.
useEffect(() => {
let timer = setInterval(updateNotSeenAmount, 2000)
return () => clearInterval(timer)
}, [notSeenAmount])
REF: Tip: Optimizing Performance by Skipping Effects
Custom Hook Solution (ReactJs/NextJs)
Create a new folder named 'shared' and add two folders named 'hooks', 'utils' in it. Add a new file called 'commonFunctions.js' inside utils folder and add the code snippet below.
export const promisify = (fn) => {
return new Promise((resolve, reject) => {
fn
.then(response => resolve(response))
.catch(error => reject(error));
});
};
Add a new file called 'fetch-hook.js' inside hooks folder and add the code snippet below.
import { useCallback, useEffect, useRef } from "react";
import { promisify } from "../utils/commonFunctions";
export const useFetch = () => {
const isUnmounted = useRef(false);
useEffect(() => {
isUnmounted.current = false;
return () => {
isUnmounted.current = true;
};
}, []);
const call = useCallback((fn, onSuccess, onError = null) => {
promisify(fn).then(response => {
console.group('useFetch Hook response', response);
if (!isUnmounted.current) {
console.log('updating state..');
onSuccess(response.data);
}
else
console.log('aborted state update!');
console.groupEnd();
}).catch(error => {
console.log("useFetch Hook error", error);
if (!isUnmounted.current)
if (onError)
onError(error);
});
}, []);
return { call }
};
Folder Structure
Our custom hook is now ready. We use it in our component like below
const OurComponent = (props) => {
//..
const [subscriptions, setSubscriptions] = useState<any>([]);
//..
const { call } = useFetch();
// example method, change with your own
const getSubscriptions = useCallback(async () => {
call(
payment.companySubscriptions(userId), // example api call, change with your own
(data) => setSubscriptions(data),
);
}, [userId]);
//..
const updateSubscriptions = useCallback(async () => {
setTimeout(async () => {
await getSubscriptions();
}, 5000);// 5 seconds delay
}, [getSubscriptions]);
//..
}
In our component, we call 'updateSubscriptions' method. It will trigger 'getSubscriptions' method in which we used our custom hook. If we try to navigate to a different page after calling updateSubscriptions method before 5 seconds over, our custom hook will abort state update and prevent that warning on the title of this question
Wanna see opposite?
Change 'getSubscriptions' method with the one below
const getSubscriptions = useCallback(async () => {
const response = await payment.companySubscriptions(userId);
setSubscriptions(response);
}, [userId]);
Now try to call 'updateSubscriptions' method and navigate to a different page before 5 seconds over
Try this custom hook:
import { useEffect, useRef } from 'react';
export const useIsMounted = () => {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => (isMounted.current = false);
}, []);
return isMounted;
};
function Example() {
const isMounted = useIsMounted();
const [text, setText] = useState();
const safeSetState = useCallback((callback, ...args) => {
if (isMounted.current) {
callback(...args);
}
}, []);
useEffect(() => {
safeSetState(setText, 'Hello')
});
}, []);
return <h2>{text}</h2>;
}

How to send request on click React Hooks way?

How to send http request on button click with react hooks? Or, for that matter, how to do any side effect on button click?
What i see so far is to have something "indirect" like:
export default = () => {
const [sendRequest, setSendRequest] = useState(false);
useEffect(() => {
if(sendRequest){
//send the request
setSendRequest(false);
}
},
[sendRequest]);
return (
<input type="button" disabled={sendRequest} onClick={() => setSendRequest(true)}
);
}
Is that the proper way or is there some other pattern?
export default () => {
const [isSending, setIsSending] = useState(false)
const sendRequest = useCallback(async () => {
// don't send again while we are sending
if (isSending) return
// update state
setIsSending(true)
// send the actual request
await API.sendRequest()
// once the request is sent, update state again
setIsSending(false)
}, [isSending]) // update the callback if the state changes
return (
<input type="button" disabled={isSending} onClick={sendRequest} />
)
}
this is what it would boil down to when you want to send a request on click and disabling the button while it is sending
update:
#tkd_aj pointed out that this might give a 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 a useEffect cleanup function."
Effectively, what happens is that the request is still processing, while in the meantime your component unmounts. It then tries to setIsSending (a setState) on an unmounted component.
export default () => {
const [isSending, setIsSending] = useState(false)
const isMounted = useRef(true)
// set isMounted to false when we unmount the component
useEffect(() => {
return () => {
isMounted.current = false
}
}, [])
const sendRequest = useCallback(async () => {
// don't send again while we are sending
if (isSending) return
// update state
setIsSending(true)
// send the actual request
await API.sendRequest()
// once the request is sent, update state again
if (isMounted.current) // only update if we are still mounted
setIsSending(false)
}, [isSending]) // update the callback if the state changes
return (
<input type="button" disabled={isSending} onClick={sendRequest} />
)
}
You don't need an effect to send a request on button click, instead what you need is just a handler method which you can optimise using useCallback method
const App = (props) => {
//define you app state here
const fetchRequest = useCallback(() => {
// Api request here
}, [add dependent variables here]);
return (
<input type="button" disabled={sendRequest} onClick={fetchRequest}
);
}
Tracking request using variable with useEffect is not a correct pattern because you may set state to call api using useEffect, but an additional render due to some other change will cause the request to go in a loop
In functional programming, any async function should be considered as a side effect.
When dealing with side effects you need to separate the logic of starting the side effect and the logic of the result of that side effect (similar to redux saga).
Basically, the button responsibility is only triggering the side effect, and the side effect responsibility is to update the dom.
Also since react is dealing with components you need to make sure your component still mounted before any setState or after every await this depends on your own preferences.
to solve this issue we can create a custom hook useIsMounted this hook will make it easy for us to check if the component is still mounted
/**
* check if the component still mounted
*/
export const useIsMounted = () => {
const mountedRef = useRef(false);
const isMounted = useCallback(() => mountedRef.current, []);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
});
return isMounted;
};
Then your code should look like this
export const MyComponent = ()=> {
const isMounted = useIsMounted();
const [isDoMyAsyncThing, setIsDoMyAsyncThing] = useState(false);
// do my async thing
const doMyAsyncThing = useCallback(async () => {
// do my stuff
},[])
/**
* do my async thing effect
*/
useEffect(() => {
if (isDoMyAsyncThing) {
const effect = async () => {
await doMyAsyncThing();
if (!isMounted()) return;
setIsDoMyAsyncThing(false);
};
effect();
}
}, [isDoMyAsyncThing, isMounted, doMyAsyncThing]);
return (
<div>
<button disabled={isDoMyAsyncThing} onClick={()=> setIsDoMyAsyncThing(true)}>
Do My Thing {isDoMyAsyncThing && "Loading..."}
</button>;
</div>
)
}
Note: It's always better to separate the logic of your side effect from the logic that triggers the effect (the useEffect)
UPDATE:
Instead of all the above complexity just use useAsync and useAsyncFn from the react-use library, It's much cleaner and straightforward.
Example:
import {useAsyncFn} from 'react-use';
const Demo = ({url}) => {
const [state, doFetch] = useAsyncFn(async () => {
const response = await fetch(url);
const result = await response.text();
return result
}, [url]);
return (
<div>
{state.loading
? <div>Loading...</div>
: state.error
? <div>Error: {state.error.message}</div>
: <div>Value: {state.value}</div>
}
<button onClick={() => doFetch()}>Start loading</button>
</div>
);
};
You can fetch data as an effect of some state changing like you have done in your question, but you can also get the data directly in the click handler like you are used to in a class component.
Example
const { useState } = React;
function getData() {
return new Promise(resolve => setTimeout(() => resolve(Math.random()), 1000))
}
function App() {
const [data, setData] = useState(0)
function onClick() {
getData().then(setData)
}
return (
<div>
<button onClick={onClick}>Get data</button>
<div>{data}</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>
You can define the boolean in the state as you did and once you trigger the request set it to true and when you receive the response set it back to false:
const [requestSent, setRequestSent] = useState(false);
const sendRequest = () => {
setRequestSent(true);
fetch().then(() => setRequestSent(false));
};
Working example
You can create a custom hook useApi and return a function execute which when called will invoke the api (typically through some onClick).
useApi hook:
export type ApiMethod = "GET" | "POST";
export type ApiState = "idle" | "loading" | "done";
const fetcher = async (
url: string,
method: ApiMethod,
payload?: string
): Promise<any> => {
const requestHeaders = new Headers();
requestHeaders.set("Content-Type", "application/json");
console.log("fetching data...");
const res = await fetch(url, {
body: payload ? JSON.stringify(payload) : undefined,
headers: requestHeaders,
method,
});
const resobj = await res.json();
return resobj;
};
export function useApi(
url: string,
method: ApiMethod,
payload?: any
): {
apiState: ApiState;
data: unknown;
execute: () => void;
} {
const [apiState, setApiState] = useState<ApiState>("idle");
const [data, setData] = useState<unknown>(null);
const [toCallApi, setApiExecution] = useState(false);
const execute = () => {
console.log("executing now");
setApiExecution(true);
};
const fetchApi = useCallback(() => {
console.log("fetchApi called");
fetcher(url, method, payload)
.then((res) => {
const data = res.data;
setData({ ...data });
return;
})
.catch((e: Error) => {
setData(null);
console.log(e.message);
})
.finally(() => {
setApiState("done");
});
}, [method, payload, url]);
// call api
useEffect(() => {
if (toCallApi && apiState === "idle") {
console.log("calling api");
setApiState("loading");
fetchApi();
}
}, [apiState, fetchApi, toCallApi]);
return {
apiState,
data,
execute,
};
}
using useApi in some component:
const SomeComponent = () =>{
const { apiState, data, execute } = useApi(
"api/url",
"POST",
{
foo: "bar",
}
);
}
if (apiState == "done") {
console.log("execution complete",data);
}
return (
<button
onClick={() => {
execute();
}}>
Click me
</button>
);
For this you can use callback hook in ReactJS and it is the best option for this purpose as useEffect is not a correct pattern because may be you set state to make an api call using useEffect, but an additional render due to some other change will cause the request to go in a loop.
<const Component= (props) => {
//define you app state here
const getRequest = useCallback(() => {
// Api request here
}, [dependency]);
return (
<input type="button" disabled={sendRequest} onClick={getRequest}
);
}
My answer is simple, while using the useState hook the javascript doesn't enable you to pass the value if you set the state as false. It accepts the value when it is set to true. So you have to define a function with if condition if you use false in the usestate

Resources