'React causing: Can't perform a React state update on an unmounted component
My situation: After login I try to get username and save it to redux store after this redirect from login to home page(in this page I display list of tasks) and I'm getting: 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.
I try ususal isMounted trick but its not help.
Login.js
function getUsername(){
let username = ""
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
try {
axios.get(`${process.env.REACT_APP_API_URL}/api/get_username/`,{
headers: headers,
})
.then(response => username = response.data["username"])
.catch(error => setResponse(error.response))
} catch (err) {
console.log(err)
}
return username
}
const loginSubmit = e => {
e.preventDefault()
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
};
const body = {username: username, password: password}
try {
axios.post(`${process.env.REACT_APP_API_URL}/api/login/`, body,{
headers: headers,
})
.then(response => setResponse(response))
.catch(error => setResponse(error.response))
} catch (err) {
console.log(err)
}
dispatch({type: "SET_NAME", name:getUsername()})
Cookies.set("logged_in", "yes")
navigate("/", {replace:true})
};
Home.js
function getTasks(isMounted){
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
try {
axios.get(`${process.env.REACT_APP_API_URL}/api/tasks/`, {
headers: headers,})
.then(response => {if(isMounted ){setTasks(response.data)}})
.catch(error => setTasks(error.response))
} catch (err) {
console.log(err)
}
}
useEffect(() => {
let isMounted = true;
getTasks(isMounted);
return () => {
isMounted = false;
};
}, []);
Solution 1:[1]
You can use local storage.
Set item:
localStorage.setItem("name", JSON.stringify(name))
Get Item:
localStorage.getItem("name")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | NiNjA_CaT |