Like the title says, I want to know how to check if url has certain part of it, for example if the url is: testurl.com/id, how to check if id is present in the url? Now, why I want to know this, is because I am trying to check if id is present in my component, here is my code:
const User = (props) => {
const { name, email, status, gender, title, method } = props.location.user;
const { id } = useParams();
const [newName, setNewName] = useState(name);
const [newEmail, setNewEmail] = useState(email);
const [newStatus, setNewStatus] = useState(status);
const [newGender, setNewGender] = useState(gender);
const updateName = (e) => {
setNewName(e.target.value);
};
const updateEmail = (e) => {
setNewEmail(e.target.value);
};
const updateStatus = (e) => {
setNewStatus(e.target.value);
};
const updateGender = (e) => {
setNewGender(e.target.value);
};
const updateData = () => {
if (method === "put") {
axios
.put(
`${process.env.REACT_APP_API_URL}users/${id}`,
{
name: newName,
email: newEmail,
status: newStatus,
gender: newGender,
},
{
headers: {
Authorization: `Bearer ${process.env.REACT_APP_API_TOKEN}`,
},
}
)
.catch(function (error) {
if (error.response.status === 422) {
alert(
"Error: The format of email is wrong! Please put it like this: yourname@yourname.com"
);
}
});
} else if (method === "post") {
axios
.post(
`${process.env.REACT_APP_API_URL}users/`,
{
name: newName,
email: newEmail,
status: newStatus,
gender: newGender,
},
{
headers: {
Authorization: `Bearer ${process.env.REACT_APP_API_TOKEN}`,
},
}
)
.catch(function (error) {
if (error.response.status === 422) {
alert("Error: Name or email already taken!");
}
});
}
};
As you can see, in this component I have a function: const updateData = ()=>... and inside the function I am checking if the method is put do this, and if the method is post do that. How do I check if the id is present in the url then do the put method, and if it isn't then do the post method. So i can then check the method without using props that are passed using Link.