OtherUserProfile.js:11 Uncaught TypeError: Cannot read properties of undefined (reading 'includes') at OtherUserProfile (OtherUserProfile.js:11:1)
import "./Profile.css"
import { UserContext } from "../App";
import { useParams } from "react-router-dom";
function OtherUserProfile() {
const [userProfile, setUserProfile] = useState();
const { state, dispatch } = useContext(UserContext);
const { userId } = useParams();
// error line
const [showFollow, setShowFollow] = useState(state ? !state.following.includes(userId) : true);
useEffect(() => {
fetch(`/user/${userId}`, {
method: "get",
headers: {
"Authorization": "Bearer " localStorage.getItem("token")
}
})
.then(response => response.json())
.then(function (data) {
console.log(data);
setUserProfile(data);
}).catch(error => {
console.log(error);
});
}, []);``` // we want to lad only once when component is mounting/loading that is why an empty array as dependency
CodePudding user response:
Issue
The basic gist is that state.following
is undefined.
const { state, dispatch } = useContext(UserContext);
...
const [showFollow, setShowFollow] = useState(state
? !state.following.includes(userId)
: true
);
Solution
You can add a null-check (Optional-Chaining operator) to guard against an "accidental" undefined access:
const [showFollow, setShowFollow] = useState(state?.following
? !state.following.includes(userId)
: true
);
You could ensure that the UserContext
is providing a state
object with a defined following
array.
const value = {
state: {
....
following: /* some array value */ || [], // <-- provided fallback
},
dispatch,
};
...
<UserContext.Provider value={value}>
...
</UserContext.Provider>