'How to display response error when it exists but is unknown until received

Using Redux Toolkit I have an asyncThunk which I would like to display errors from. When I try:

The thunk:

// Save a new role
export const saveRole = createAsyncThunk(
  "roles/saveRole",
  async (role, { rejectWithValue }) => {
    try {
      const response = await api.post("/api/roles/", role);
      return response.data;
    } catch (err) {
      return rejectWithValue(err.response.data);
    }
  }
);

The reducer:

      .addCase(saveRole.rejected, (state, action) => {
        state.error = action.payload;
        state.isLoading = false;
      });

The div I want to display an error:

      {roles.error && (
        <div className="error-container">
          {roles.error.employee_type}
        </div>
      )}

Which gives this error:

Uncaught TypeError: Cannot read properties of null (reading 'employee_type')

What I want is to be able to identify if the error is about a specific field, and if so, target that exact field.



Solution 1:[1]

Found this weird syntax for resolving the issue. It seems to check if the item exists only when it is not undefined:

      {roles.error?.employee_type && (
        <div className="error-container">
          {roles.error.employee_type}
        </div>
      )}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Alford