I'm using React and redux-toolkit for front-end development. When I try to map() the array inside of the object whole screen goes blank. This is the data structure that I'm getting from the redux state. data structure image This is the screen where I have call the state from the redux store:
const { id } = useParams();
const { mocktest, isLoading, isError, message } = useSelector(
(state) => state.mocktest
);
console.log(mocktest);
useEffect(() => {
if (isError) {
toast.error(message);
}
dispatch(getMockTestById(id));
}, [isError, message, dispatch, id]);
This is my slice:
export const getMockTestById = createAsyncThunk(
'mocktest/getMockTestById',
async (id, thunkAPI) => {
try {
// const token = thunkAPI.getState().auth.user.token;
return await mockTestServices.getMockTestById(id);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message)
error.message
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
This is how I'm trying to map() or access the data:
{mocktest.questionSet.map((qSet) => (
<h4 className="text-center">{qSet.setName}</h4>
))}
This is what I was expecting setName to be displayed in h4 tag I have also tried adding this.props.
Here is the CodeSandBox of given scenarios
Here you have missed the optional chaining before map function as it validates whether array you are mapping is invalid or not.
{mocktest?.questionSet?.map((qSet) => (
<div key={qSet._id} id="body">