useParam returns string | undefined, but the function requires a string | MutationSelection.
I have error An argument of type "string | undefined" cannot be assigned to a parameter of type "string | MutationSelection". The type "undefined" cannot be assigned to the type "string | MutationSelection".ts(2345)
.
here is my code
const PinDetail: React.FC<PropsType> = ({ user }) => {
const { pinId } = useParams()
const addComment = () => {
client.patch(pinId) //here error
.setIfMissing({ comments: [] })
.insert('after', 'comments[-1]', [{
comment,
_key: uuidv4(),
postedBy: {
_type: 'postedBy',
_ref: user._id
}
}])
.commit()
.then(() => {
fetchPinDetail(), // and here
setComment('')
setAddingComment(false)
})
}
}
client is object from sanity.io
CodePudding user response:
You need to check pinId
is not undefined before call client.patch
CodePudding user response:
I see two way of fixing this:
- Simply add an
if
condition inaddComment
function
const addComment = () => {
if (pinId) {
client
.patch(pinId)
.setIfMissing({ comments: [] })
.insert('after', 'comments[-1]', [
{
comment,
_key: uuidv4(),
postedBy: {
_type: 'postedBy',
_ref: user._id,
},
},
])
.commit()
.then(() => {
// line ended by , instead of ;
fetchPinDetail();
setComment('');
setAddingComment(false);
});
}
};
- Or handle this outside
addComment
const { pinId } = useParams();
if (!pinId) {
throw new Error('Unexpected undefined pin id');
}
Here I've thrown and error to ensure that pinId
will be defined in addComment
but you can handle this differently. For instance you could redirect user to another route or return an error message in JSX.