I have all the needed working pieces of the React Redux-toolkit working but I can’t seem to get my data to display in the component. I’m getting the error:
TypeError: noticesType.map is not a function
> 31 | {noticesType.map((post, index) => {
| ^
32 | <li key={index}>
When I Google the error. When I see is that I’m most likely passing an object when it’s looking for an array. I am pretty sure I have it set up correctly. I have The Redux DevTools open, and it shows me the correct data coming back from the API call. After 3 days of searching the web, this is where I’m at. If there is more code or anything I’ve missed please let me know.
page.tsx
export default function page() {
const dispatch = useAppDispatch();
const {noticesType, loading, error} = useAppSelector(state => state.noticesReducer)
useEffect(() => {
dispatch(fetchNotices())
}, [dispatch])
return (
<>
<div>
<h1>Notices</h1>
<ul>
<>
{noticesType.map((post, index) => {
<li key={index}>
{post.Title}
</li>
})}
</>
</ul>
</div>
</>
)
}
noticesTypes.ts
export type NoticesType = {
noticesType: NoticeType[],
createdDateTime: Date | string,
title: string,
version: string,
}
export type NoticeType = {
id: string,
Title: string,
Description: string,
startDateTime: Date | string,
endDateTime: Date | string,
planned: boolean,
}
notice.ts / noticeSlice
type NoticeState = NoticesType & {
loading: boolean,
error: boolean
}
const initialState: NoticeState = {
noticesType: [],
createdDateTime: '',
title: '',
version: '',
loading: false,
error: false
}
export const fetchNotices = createAsyncThunk('fetchNotices', async (thunkApi,{rejectWithValue}) => {
try {
const response = await fetch("https://API_CALL/notice")
return await response.json();
} catch (error) {
return rejectWithValue("Something isn't working");
}
});
export const noticeSlice = createSlice({
name: 'notices',
initialState,
reducers: {
setNotice: (state, action) => {
state.noticesType = action.payload
},
getNotice: (state, action) => {
return action.payload.notices
},
},
extraReducers: (builder) => {
builder
.addCase(fetchNotices.pending, (state, action) => {
state.loading = true;
})
.addCase(fetchNotices.fulfilled, (state, action) => {
state.loading = false,
state.noticesType = action.payload
})
.addCase(fetchNotices.rejected, (state, {payload}) => {
state.loading = true
})
}
})
export const {
getNotice,
setNotice,
} = noticeSlice.actions
export default noticeSlice.reducer
index.ts / store
export const store = configureStore({
reducer: {
noticesReducer,
},
middleware: getDefaultMiddleware => getDefaultMiddleware({serializableCheck: false})
})
console.log(store.getState());
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch