react-router#useNavigate JavaScript Examples

The following examples show how to use react-router#useNavigate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProductAddEdit.js    From react-sample-projects with MIT License 4 votes vote down vote up
ProductAddEdit = () => {
  const categories = useSelector(state => state.product.categories);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const initialValues = {
    title: '',
    price: '',
    category: '',
    description: '',
    image: '',
  };

  const validationSchema = yup.object({
    title: yup.string().required(),
    price: yup.number().required(),
    category: yup.string().required(),
    description: yup.string().required(),
    image: yup.string().url().required(),
  });

  const onFormSubmit = (values, actions) => {
    actions.setSubmitting(false);
    dispatch(addNewProduct(values));
    navigate('/');
  };

  useEffect(() => {
    dispatch(fetchCategories());
    return () => {};
  }, [dispatch]);

  return (
    <Box boxShadow="base" m={'auto'} width="clamp(300px, 60%, 100%)">
      <Formik
        initialValues={initialValues}
        onSubmit={onFormSubmit}
        validationSchema={validationSchema}
      >
        {props => (
          <Form noValidate>
            <VStack p={3} m="3">
              <Box fontWeight="semibold" mt="1" as="h2" textAlign="left">
                Add Product
              </Box>

              <Field name="title">
                {({ field, form }) => (
                  <FormControl
                    isRequired
                    isInvalid={form.errors.title && form.touched.title}
                  >
                    <FormLabel htmlFor="title">Enter Title</FormLabel>
                    <Input
                      {...field}
                      type="text"
                      id="title"
                      placeholder="Enter Title"
                    />
                    <ErrorMessage
                      name="title"
                      component={FormErrorMessage}
                    ></ErrorMessage>
                  </FormControl>
                )}
              </Field>

              <Field name="price">
                {({ field, form }) => (
                  <FormControl
                    isRequired
                    isInvalid={form.errors.price && form.touched.price}
                  >
                    <FormLabel>Enter price</FormLabel>
                    <Input type="number" placeholder="Enter price" {...field} />
                    <ErrorMessage
                      name="price"
                      component={FormErrorMessage}
                    ></ErrorMessage>
                  </FormControl>
                )}
              </Field>
              <Field name="category">
                {({ field, form }) => (
                  <FormControl
                    name="category"
                    isRequired
                    isInvalid={form.errors.category && form.touched.category}
                  >
                    <FormLabel>Enter category</FormLabel>
                    <Select placeholder="Select category" {...field}>
                      {categories.map((category, index) => (
                        <option key={index}>{category}</option>
                      ))}
                    </Select>
                    <ErrorMessage
                      name="category"
                      component={FormErrorMessage}
                    ></ErrorMessage>
                  </FormControl>
                )}
              </Field>
              <Field name="description">
                {({ field, form }) => (
                  <FormControl
                    name="description"
                    isRequired
                    isInvalid={
                      form.errors.description && form.touched.description
                    }
                  >
                    <FormLabel>Enter description</FormLabel>
                    <Textarea
                      {...field}
                      id="description"
                      placeholder="Enter description"
                    ></Textarea>
                    <ErrorMessage
                      name="description"
                      component={FormErrorMessage}
                    ></ErrorMessage>
                  </FormControl>
                )}
              </Field>
              <Field name="image">
                {({ field, form }) => (
                  <FormControl
                    name="image"
                    isRequired
                    isInvalid={form.errors.image && form.touched.image}
                  >
                    <FormLabel>Enter image</FormLabel>
                    <Input
                      type="url"
                      placeholder="Enter image url"
                      {...field}
                    />

                    <ErrorMessage
                      name="image"
                      component={FormErrorMessage}
                    ></ErrorMessage>
                  </FormControl>
                )}
              </Field>
              <Button
                mt={4}
                colorScheme="teal"
                type="submit"
                isLoading={props.isSubmitting}
              >
                Add Product
              </Button>
            </VStack>
          </Form>
        )}
      </Formik>
    </Box>
  );
}
Example #2
Source File: ManageUsersTable.js    From serverless-media-portal with MIT License 4 votes vote down vote up
export default function ManageUsersTable() {
	const [isLoading, setIsLoading] = useState(true);
	const [users, setUsers] = useState([]);
	const [selectedUser, setSelectedUser] = useState({});
	const [userIsBeingEdited, setUserIsBeingEdited] = useState(false);
	const [modalIsOpen, setModalIsOpen] = useState(false);
	const { addToast } = useToasts();
	const navigate = useNavigate();

	useEffect(() => {
		setIsLoading(true);
		loadUsers();
	}, []);

	const loadUsers = async () => {
		const res = await authGet("http://localhost:3001/dev/listUsers");

		if (res && res.users) {
			setUsers(res.users);
			setIsLoading(false);
		}
	};

	const onEditClicked = userHash => {
		setModalIsOpen(true);
		setUserIsBeingEdited(true);
		setSelectedUser(users.find(x => x.UserHash === userHash));
	};

	const onDeleteClicked = (userToDelete) => {
		const msg = userToDelete.UserHash === "$2a$10$yGsdhh0HUIWMoECia9IcLeY2R8VMPeYLWSskup3bqHdbVAmNnGNRi"
			? "Are you sure you want to delete the temporary admin user? If you haven't created another admin user, you will lose access to this page"
			: `Are you sure you wish to delete ${userToDelete.DisplayName} ?`;

		if (window.confirm(msg)) {
			deleteUser(userToDelete.UserHash);
		}
	};

	const deleteUser = async userHash => {
		setIsLoading(true);
		const res = await authGet(`http://localhost:3001/dev/deleteUser?userHash=${userHash}`);

		if (res && res.success) {
			addNotification("User deleted", "success");

			// When users delete the temporary admin, immediately redirect them to login
			if (userHash === "$2a$10$yGsdhh0HUIWMoECia9IcLeY2R8VMPeYLWSskup3bqHdbVAmNnGNRi") {
				navigate("/");
				window.location.reload("/");
			} else {
				await loadUsers();
			}
		} else {
			addNotification("Error deleting user", "error");
		}
	};

	const onAddUserClicked = () => {
		setModalIsOpen(true);
		setUserIsBeingEdited(false);
	};

	const addNotification = (msg, type) => {
		addToast(msg, {
			appearance: type,
			autoDismiss: true
		});
	};

	const onModalClosed = (performReload) => {
		setModalIsOpen(false);
		setSelectedUser({});

		if (performReload === true) {
			setIsLoading(true);
			loadUsers();
		}
	};

	return (
		<>
			<Table className="mb-5" striped bordered hover responsive>
				<thead>
					<tr>
						<th colSpan="99" className="text-center bg-white">
							<div className="d-inline-block pt-1">Manage Users</div>
							<Button
								variant="success"
								size="sm"
								className="float-right"
								onClick={() => onAddUserClicked()}
							>
								Add User
							</Button>
						</th>
					</tr>
					<tr>
						<th style={{ width: "300px" }}>Name</th>
						<th>Hash</th>
						<th>Tags</th>
						<th style={{ width: "130px" }}></th>
					</tr>
				</thead>
				<tbody>
					{isLoading ? (
						<tr>
							<td colSpan="4" className="text-center">
								<Spinner animation="border" size="sm" />
							</td>
						</tr>
					) : (
						users.map(user => (
							<tr key={user.DisplayName}>
								<td>{user.DisplayName}</td>
								<td style={{ maxWidth: "100px", textOverflow: "ellipsis", overflow: "hidden" }} title={user.UserHash}>{user.UserHash}</td>
								<td>{user.Tags.join(", ")}</td>
								<td>
									<Button
										variant="warning"
										size="sm"
										className="ml-auto mr-1"
										onClick={() => onEditClicked(user.UserHash)}
										disabled={user.UserHash === "$2a$10$yGsdhh0HUIWMoECia9IcLeY2R8VMPeYLWSskup3bqHdbVAmNnGNRi"}
									>
										Edit
									</Button>
									<Button
										variant="danger"
										size="sm"
										className="ml-auto"
										onClick={() => onDeleteClicked(user)}
										disabled={users.length === 1}
									>
										Delete
									</Button>
								</td>
							</tr>
						))
					)}
				</tbody>
			</Table>

			<AddOrEditUserModal
				user={selectedUser}
				isOpen={modalIsOpen}
				close={onModalClosed}
				editUserMode={userIsBeingEdited}
			/>
		</>
	);
}