I have a functional component and everything is working well but I get this error when reloading the page :
TypeError: Cannot read property 'pourcent' of undefined
Here is the component :
import Button_Drop from "../../../../components/Buttons/Button_Drop";
import Chart_Objectif from "../../../../components/Charts/Chart_Objectif";
import { useDispatch, useSelector } from "react-redux";
import { getAllTcheksByEtat } from "../../../../actions/tcheks.action";
function Card_Objectifs() {
const objectif = useSelector((state: any) => state.objectifsReducer.getMonthObjectif);
console.log(objectif);
return (
<div className="ObjCard">
<div className="titleObj">
<h1>Ce mois</h1>
<Button_Drop
name="Total"
section={["VDR", "FLASH", "EDL", "DIAGS", "VV", "CATNAT", "DEFIB", "Total"]}
onclick={() => {}}
data={[]}
/>
</div>
<div className="chartWrapper">
<Chart_Objectif data={objectif.pourcent.replace("%", "")} />
</div>
<div className="goalWrapper">
<div className="goalCard">
<h2>Complétés</h2>
<h3>{objectif.validation}</h3>
</div>
<div className="goalCard">
<h2>Objectif</h2>
<h3>{objectif.objectifs}</h3>
</div>
</div>
</div>
);
}
export default Card_Objectifs;
Here is the action :
export const getMonthObjectif = () => {
return (dispatch: any) => {
dispatch(isLoading(true));
return axios
.get(`objectif/getMonthObjectif`)
.then((res) => {
dispatch(isLoading(false));
dispatch({ type: GET_MONTH_OBJECTIF, payload: res.data });
})
.catch((err) => {
console.log(err);
dispatch(isLoading(false));
});
};
};
The reducer file :
import {
GET_ALL_OBJECTIFS,
GET_ALL_OBJECTIFS_SPE,
GET_MONTH_OBJECTIF,
} from "../actions/objectifs.action";
const initialState = {};
export default function objectifsReducer(state = initialState, action: any) {
switch (action.type) {
case GET_ALL_OBJECTIFS:
return {
...state,
getAllObjectifs: action.payload,
};
case GET_ALL_OBJECTIFS_SPE:
return {
...state,
getAllObjectifsSpe: action.payload,
};
case GET_MONTH_OBJECTIF:
return {
...state,
getMonthObjectif: action.payload,
};
default:
return state;
}
}
It makes the same error with other datas i'm trying to display after reload (objectif.validation and objectif.objectifs).
Thank you
pourcentdoesn't exit in empty object. You can try these options: 1. Create a blank structure as ur initial state, so there is some default data. 2. Use a loading flag to represent api request status in redux and don't render/read state until it's true.