React-Redux render refresh crash

Viewed 662

I have an Mern app with Redux. I have a problem. Profiles component crashes in two circumstances. 1)after page refreshes in build version.2)When going Proiles routes from directly address bar.(Shorter code for reducing the size)

1)Profiles.js component renders all profiles come from redux state via "getProfiles" action method.

 return (
    <Fragment>
      {loading ? (
        <Spinner />
      ) : (
        <Fragment>
          <h1 className="large text-primary">Profiles</h1>
          <p className="lead">Üyeleri ve grupları keşfedin</p>
          <div className="form">
            <div className="form-group">
              <input
                type="text"
                placeholder="İsim"
                name="company"
                value={company}
                onChange={(e) => onChange(e)}
              />{" "}
            </div>{" "}
          </div>
          <div
            className=" lead d-flex align-items-center"
            onClick={() => setOpen(!open)}
          >
          </div>
          <div className="profiles">
            {profiles.length > 0 ? (
              profiles.map(
                (profile) =>
                  profile.user._id !== user._id && (
                    <ProfileItem
                      key={profile._id}
                      followUser={followUser}
                      unFollowUser={unFollowUser}
                      profile={profile}
                      user={user}
                    />
                  )
              )
            ) : (
              <h4>No Profile</h4>
            )}
          </div>
        </Fragment>
      )}
    </Fragment>
  );
};

Redux Action for Profiles.js

export const getProfiles = (
  page,
  start,
  graduation,
  mentorship,
  scholarship,
  representative,
  company
) => async (dispatch) => {
   const limit = 10;
  const payload = {
    params: {
      page,
      start,
      limit,
      graduation,
      mentorship,
      scholarship,
      representative,
      company,
    },
  };
  console.log(page);
  console.log(payload);
  try {
    const res = await axios.get("/api/profile", payload);
    console.log(res.data.profiles);
    dispatch({
      type: GET_PROFILES,
      payload: { profiles: res.data.profiles, totalPages: res.data.totalPages },
    });
    console.log(res.data);
  } catch (err) {
    dispatch({
      type: PROFILE_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};

Reducer for Profiles.js

  case GET_PROFILES:
  return {
    ...state,
    profiles: payload.profiles,
    totalPage: payload.totalPages,
    loading: false,
  };

When i click from navigation with React-routers component its fine. But when i refresh or goes to page directly from address bar it crashes.And these error in console

Refresh/address bar render crash

Page only crashes in buid mode. Fine in development mode. I tried to change conditionals (loading etc..)but nothing has changed.

Any help would be appreciated. Thank you!

2 Answers

It seems the issue is not with the profile rather with user _id. Initially, at first render of your Profile component, user is null, thus you are getting error _id of null.

Try to check if user exists, then render profile. Like in Profile.js

if(!user){
        return null
        }

        return (
    <Fragment> 
    // yor rest code
    </Fragment>

Also, check if profile's user attribute appearing null, after page load using console.log.

I'm not sure but you can validate to avoid the first error, I mean the '_id' error:

<div className="profiles">
  { 
    profiles.length > 0 && user ? (
      profiles.map((profile) => {
        if (profile.user && profile.user._id !== user._id) {
          return (
            <ProfileItem
              key={profile._id}
              followUser={followUser}
              unFollowUser={unFollowUser}
              profile={profile}
              user={user}
            />
          );
        }
      })
    ) : (
      <h4>No Profile</h4>
    )
  }
</div>;

The statusText error is because there is an error in your try catch inside profiles.js and when you want to dispatch a PROFILE_ERROR action, you are trying to access to statusText from err.response.statusText but err.response is undefined.

Related