2

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

5
  • Add a line <pre>{JSON.stringify(mocktest, null, 2)</pre> and check what's the content of pre element. Commented Nov 27, 2022 at 12:01
  • It shows all the data that fetched from the backend via redux and axios Commented Nov 27, 2022 at 13:57
  • It's look like your initial state is undefined and the page just crashed. Try to check the value of mocktest in that component and if value is undefined, add some checks there Commented Nov 27, 2022 at 17:19
  • @MuhammadNoumanRafique The initial state of mocktest has all the required data. After mapping like this all page goes white {mocktest.questionSet.map((qSet) => ( <h4 className="text-center">{qSet.setName}</h4> ))} Commented Nov 27, 2022 at 17:59
  • Can you create a sandbox for your code so someone can help you to find that issue? Commented Nov 28, 2022 at 0:52

1 Answer 1

1

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">
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is correct - but this is not a ternary operator; this is optional chaining

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.