I am trying to loop over the items i am receiving in my slice but i am getting the error Cannot read properties of undefined (reading 'map'), i am new to redux i am just trying to learn the pattern here, the connection between the backend and frontend is fine as i tried it before adding redux.
my homescreen component :
function HomeScreen() {
const dispatch = useDispatch();
const Listvessel = useSelector((state) => state.vesselList.value);
const { error, loading, vessels } = Listvessel;
useEffect(() => {
dispatch(vesselList());
}, [dispatch]);
return (
<div>
Fleet vessels :
<div className="fleet-vessels-info">
{vessels.map((vessel) => (
<VesselCard vessel={vessel} />
))}
</div>
</div>
);
}
export default HomeScreen;
the slice called vessels :
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
import {
VESSEL_LIST_REQUEST,
VESSEL_LIST_SUCCESS,
VESSEL_LIST_FAIL,
} from "../constants/vesselConstants";
export const vesselSlice = createSlice({
name: "vesselList",
initialState: {
value: {
name: "",
component_count: 0,
inventory_item_count: 0,
image: "",
},
},
reducers: {
vesselList: (state, action) => {
state.value = action.payload;
},
},
});
export const {
vesselList,
} =
(keyword = "") =>
async (dispatch) => {
try {
dispatch({ type: VESSEL_LIST_REQUEST });
const { data } = await axios.get(
"http://127.0.0.1:8000/api/vessels/info"
);
dispatch({
type: VESSEL_LIST_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: VESSEL_LIST_FAIL,
payload:
error.response && error.response.data.detail
? error.response.data.detail
: error.message,
});
}
};
export default vesselSlice.reducer;
how the api look
[
{
"id": 1,
"component_count": 3,
"inventory_item_count": 1,
"name": "Aylah",
"imo": "Aylah123",
"image": "http://127.0.0.1:8000/media/vessel_image/aylah.jpg"
},]
Actually, I can't see where vessels
is defined, it might be Listvessel
instead, but still, it might throw an error, because it might not have loaded yet from API. So you might have to check if the variable is null or empty at first. some thing like:
if(!Listvessel){
return "Loading..."
}
return (
<div> //your data or .map function</div>
)