I get this error when I run my ReactJs code:
index.js:1375 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.
I tried the below code, but i still get the same error. I see code on stackoverflow with the API call in componentDidMount, but mine is coming from Redux. How do I unsubscribe or cancel subscriptions and async tasks in componentWillUnmount?
Been struggling with this all night long.
This is my Reducers:
const initState = {
error_message: null,
patient : null,
isLoading: true,
patients: [],
}
const patientReducer = (state = initState, action) => {
switch (action.type){
case ALL_PATIENT_ERROR:
case SHOW_PATIENT_ERROR:
console.log(action.payload)
return {
...state,
error_message: action.payload
}
case SHOW_PATIENT_SUCCESS:
return {
...state,
patient : action.payload.patient,
isLoading: false
}
case ALL_PATIENT_SUCCESS:
return {
...state,
patients : action.payload,
isLoading: false
}
default:
return state
}
}
Component:
class AllPatient extends Component {
_isMounted = false;
state ={
isLoading: true
}
_changeHandler = (e) => {
let data = {...this.state}
data[e.target.name] = e.target.value
this.setState(data)
}
componentDidMount = () =>{
this._isMounted = true;
this.props.getPatients()
}
componentWillUnmount = () =>{
this._isMounted = false;
this.unsubscribe();
}
render() {
console.log(this.props)
let {patients} = this.props.patients
console.log(patients)
return (
<div>
<Container>
<SearchPatients change={this._changeHandler} />
{(this.props.patients.isLoading) ? <Loading /> :
<Card>
<Card.Body>
<Card.Title>
All Patients
</Card.Title>
<Table responsive>
<thead>
<tr>
<th>#</th>
<th>Full Name</th>
<th>Phone</th>
<th>DOB</th>
<th>Email</th>
<th>Last Visit</th>
</tr>
</thead>
<tbody>
{patients.patients.map(patient =>
<PatientList key={patient._id} patient={patient}/>
)}
</tbody>
</Table>
</Card.Body>
</Card>}
</Container>
</div>
)
}
}
const mapStateToProps = (state) =>{
console.log(state)
return {
patients : state.patients,//.patients.patients,
// isLoading : state.isLoading
}
}
const mapDispatchToProps = (dispatch) =>{
return {
getPatients : () => dispatch(getAllPatients())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AllPatient)
Action:
export const getAllPatients = () => async (dispatch) => {
let token = getToken()
if(token){
try{
const response = await axios.get(`${baseUrl}/api/patients`,headerInfo,{cancelToken: source.token})
return dispatch({
type : ALL_PATIENT_SUCCESS,
payload: response.data
})
}catch(e){
console.log(e)
return dispatch({
type : ALL_PATIENT_ERROR,
payload: e.response
})
}
}else{
console.log('error')
}
}