✨ Start on error handling

♻ Use TypedDocumentNode's instead of apollo-react-typescript codegen
💄 Add toast
This commit is contained in:
nikolark committed 2021-11-06 21:49:28 +01:00
1 parent ed82ca3891
commit 0a435d3224
21 files changed
+565 -117

No files matched your search

+9 -4
View File
@@ -7,14 +7,19 @@ import styles from "./App.module.css";
import { Routes } from "./Routes";
import client from "./client";
import { Header } from "./components/Header";
import { Toast } from "./components/Toast";
import { ToastProvider } from "./components/ToastProvider";
const App: React.FC = () => (
<ApolloProvider client={client}>
<Router>
<Header />
<div className={styles.app}>
<Routes />
</div>
<ToastProvider>
<Header />
<div className={styles.app}>
<Routes />
</div>
<Toast />
</ToastProvider>
</Router>
</ApolloProvider>
);
+5
View File
@@ -0,0 +1,5 @@
.toast {
position: absolute;
bottom: 32px;
right: 32px;
}
+40
View File
@@ -0,0 +1,40 @@
import { Toast as BSToast } from "bootstrap";
import clsx from "clsx";
import React, { useEffect, useRef } from "react";
import styles from "./Toast.module.css";
import { useToast } from "./ToastProvider";
export const Toast: React.FC = () => {
const ref = useRef<HTMLInputElement>(null);
const { visible, showToast, message } = useToast();
const classes = clsx("toast align-items-center text-white bg-primary border-0", styles.toast);
useEffect(() => {
if (!ref.current) return;
const bsToast = BSToast.getInstance(ref.current) || new BSToast(ref.current);
if (visible) {
bsToast?.show();
} else if (!visible) {
bsToast?.hide();
}
return () => bsToast?.hide();
}, [visible]);
return (
<div ref={ref} className={classes} role="alert" aria-live="assertive" aria-atomic="true">
<div className="d-flex">
<div className="toast-body">{message}</div>
<button
type="button"
className="btn-close btn-close-white me-2 m-auto"
data-bs-dismiss="toast"
aria-label="Close"
onClick={() => showToast(message)}
/>
</div>
</div>
);
};
+45
View File
@@ -0,0 +1,45 @@
import React, { ReactNode, useContext, useState } from "react";
interface ToastProps {
visible: boolean;
message: string;
showToast: (message: string) => void;
hide: () => void;
}
const defaultState = {
visible: false,
message: "",
// eslint-disable-next-line @typescript-eslint/no-empty-function
showToast: () => {},
// eslint-disable-next-line @typescript-eslint/no-empty-function
hide: () => {},
};
const ToastContext = React.createContext<ToastProps>(defaultState);
type ToastProviderProps = {
children: ReactNode;
};
export const ToastProvider: React.FC<ToastProviderProps> = ({ children }) => {
const [visible, setVisible] = useState(defaultState.visible);
const [message, setMessage] = useState("");
const showToast = (newMessage: string) => {
setMessage(newMessage);
if (!visible) {
setVisible(true);
setTimeout(() => {
setVisible(false);
setMessage("");
}, 3000);
}
};
const hide = () => {
setVisible(true);
setMessage("");
};
return <ToastContext.Provider value={{ visible, showToast, message, hide }}>{children}</ToastContext.Provider>;
};
export const useToast = (): ToastProps => useContext(ToastContext);
+31 -9
View File
@@ -1,21 +1,23 @@
import { useMutation } from "@apollo/client";
import React, { useState } from "react";
import { ProductCard } from "../../components/ProductCard";
import { useToast } from "../../components/ToastProvider";
import { UserCard } from "../../components/UserCard";
import { Product, User } from "../../types";
import { CreateOrderDocument, Product, User } from "../../types";
import styles from "./Register.module.css";
import { useRegister } from "./useRegister";
const USER_EXTERNAL = "external";
type OrderLine = {
id: string;
productId: string;
amount: number;
};
const sumTotal = (products: Product[], order: OrderLine[], isExternal: boolean) => {
const prices = order.map((orderLine: OrderLine) => {
const product = products.find((product: Product) => product.id === orderLine.id);
const product = products.find((product: Product) => product.id === orderLine.productId);
if (!product) return 0;
return orderLine.amount * (isExternal ? product.salePriceExt : product.salePriceInt);
});
@@ -26,22 +28,26 @@ export const Register: React.FC = () => {
const { users, products, loading, showAll, setShowAll } = useRegister();
const [selectedUser, setSelectedUser] = useState("");
const [order, setOrder] = useState<OrderLine[]>([]);
const [createOrderMutation, { loading: mutateLoading }] = useMutation(CreateOrderDocument, {
variables: { customerId: selectedUser, orderLines: order },
});
const { showToast } = useToast();
const reset = () => {
setOrder([]);
setSelectedUser("");
};
const addToOrder = (id: string) => {
const addToOrder = (productId: string) => {
let added = false;
const newOrder = order.map((orderLine: OrderLine) => {
if (orderLine.id === id) {
if (orderLine.productId === productId) {
added = true;
return { ...orderLine, amount: orderLine.amount + 1 };
}
return orderLine;
});
if (!added) {
newOrder.push({ id, amount: 1 });
newOrder.push({ productId, amount: 1 });
}
setOrder(newOrder);
};
@@ -54,6 +60,22 @@ export const Register: React.FC = () => {
return <div>Loading...</div>;
}
const onSubmit = async () => {
let res;
try {
res = await createOrderMutation();
} catch (e) {
showToast("Whoops");
console.log("woops");
return;
}
const { data } = res;
if (data?.createOrder?.__typename === "CreateOrderSuccess") {
showToast("Woop");
return;
}
showToast("booo");
};
return (
<div>
<section>
@@ -86,8 +108,8 @@ export const Register: React.FC = () => {
key={product.id}
product={product}
onProduct={() => addToOrder(product.id)}
amount={order.find((orderLine: OrderLine) => orderLine.id === product.id)?.amount || 0}
active={order.some((orderLine: OrderLine) => orderLine.id === product.id)}
amount={order.find((orderLine: OrderLine) => orderLine.productId === product.id)?.amount || 0}
active={order.some((orderLine: OrderLine) => orderLine.productId === product.id)}
/>
))}
</div>
@@ -96,7 +118,7 @@ export const Register: React.FC = () => {
<span className={styles.total}>
Totalt: <span>{total}</span>
</span>
<button type="button" className="btn btn-primary btn-lg" onClick={() => console.log("kjøp", order)}>
<button type="button" className="btn btn-primary btn-lg" onClick={onSubmit}>
Kjøp
</button>{" "}
<button type="button" className="btn btn-outline-secondary" onClick={reset}>
@@ -0,0 +1,26 @@
mutation CreateOrder($customerId: ID!, $orderLines:[OrderLineInput!]!) {
createOrder(customerId: $customerId, orderLines: $orderLines) {
... on CreateOrderSuccess {
order {
id
customer {
id
}
orderSum
}
}
... on InsufficientFunds {
error
message
amountLacking
}
... on FormErrors {
error
message
fields {
field
message
}
}
}
}
@@ -1,7 +1,8 @@
import { useQuery } from "@apollo/client";
import { parseISO, subDays } from "date-fns";
import { useState } from "react";
import { useAllProductsQuery, useAllUsersQuery, User, Product } from "../../types";
import { User, Product, AllProductsDocument, AllUsersDocument } from "../../types";
const activeLimitDays = 365 / 2;
@@ -15,8 +16,8 @@ type useRegisterType = {
export const useRegister = (): useRegisterType => {
const [showAll, setShowAll] = useState(false);
const { data, loading } = useAllProductsQuery({ variables: { active: true } });
const { data: usersData, loading: usersLoading } = useAllUsersQuery();
const { data, loading } = useQuery(AllProductsDocument, { variables: { active: true } });
const { data: usersData, loading: usersLoading } = useQuery(AllUsersDocument);
const allUsers = usersData?.allUsers || [];
const users = showAll
+21
View File
@@ -0,0 +1,21 @@
import { useCallback, useEffect, useRef } from "react";
export function usePrevious(value: any) {
// The ref object is a generic container whose current property is mutable ...
// ... and can hold any value, similar to an instance property on a class
const ref = useRef();
// Store current value in ref
useEffect(() => {
ref.current = value;
}, [value]); // Only re-run if value changes
// Return previous value (happens before update in useEffect above)
return ref.current;
}
export function useToast() {
const show = useCallback(() => {
console.log("showing toast with element from root");
}, []);
return { show };
}
+69 -82
View File
@@ -1,10 +1,8 @@
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
import { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
const defaultOptions = {}
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
@@ -16,6 +14,64 @@ export type Scalars = {
DateTime: any;
};
export type CreateOrderResponse = CreateOrderSuccess | FormErrors | InsufficientFunds;
export type CreateOrderSuccess = {
__typename?: 'CreateOrderSuccess';
order: Order;
};
export type Error = {
error: Scalars['Boolean'];
message: Scalars['String'];
};
export type FieldError = Error & {
__typename?: 'FieldError';
error: Scalars['Boolean'];
field: Scalars['String'];
message: Scalars['String'];
};
export type FormErrors = {
__typename?: 'FormErrors';
error: Scalars['Boolean'];
fields: Array<FieldError>;
message: Scalars['String'];
};
export type InsufficientFunds = Error & {
__typename?: 'InsufficientFunds';
amountLacking: Scalars['Float'];
error: Scalars['Boolean'];
message: Scalars['String'];
};
export type Mutation = {
__typename?: 'Mutation';
createOrder: CreateOrderResponse;
};
export type MutationCreateOrderArgs = {
customerId: Scalars['ID'];
isExternal?: Scalars['Boolean'];
orderLines: Array<OrderLineInput>;
};
export type Order = {
__typename?: 'Order';
created: Scalars['DateTime'];
customer?: Maybe<User>;
id: Scalars['ID'];
orderSum: Scalars['Float'];
};
export type OrderLineInput = {
amount: Scalars['Int'];
productId: Scalars['ID'];
};
export type Product = {
__typename?: 'Product';
id: Scalars['ID'];
@@ -32,6 +88,7 @@ export type ProductFilter = {
export type Query = {
__typename?: 'Query';
allOrders: Array<Order>;
allProducts: Array<Product>;
allUsers: Array<User>;
};
@@ -69,85 +126,15 @@ export type AllUsersQueryVariables = Exact<{ [key: string]: never; }>;
export type AllUsersQuery = { __typename?: 'Query', allUsers: Array<{ __typename?: 'User', id: string, firstName: string, lastName: string, profile?: { __typename?: 'UserProfile', id: string, balance: number, image: string, lastPurchaseDate: any } | null | undefined }> };
export type CreateOrderMutationVariables = Exact<{
customerId: Scalars['ID'];
orderLines: Array<OrderLineInput> | OrderLineInput;
}>;
export const AllProductsDocument = gql`
query allProducts($active: Boolean!) {
allProducts(filters: {active: $active}) {
id
name
imageUrl
salePriceExt
salePriceInt
}
}
`;
/**
* __useAllProductsQuery__
*
* To run a query within a React component, call `useAllProductsQuery` and pass it any options that fit your needs.
* When your component renders, `useAllProductsQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useAllProductsQuery({
* variables: {
* active: // value for 'active'
* },
* });
*/
export function useAllProductsQuery(baseOptions: Apollo.QueryHookOptions<AllProductsQuery, AllProductsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<AllProductsQuery, AllProductsQueryVariables>(AllProductsDocument, options);
}
export function useAllProductsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<AllProductsQuery, AllProductsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<AllProductsQuery, AllProductsQueryVariables>(AllProductsDocument, options);
}
export type AllProductsQueryHookResult = ReturnType<typeof useAllProductsQuery>;
export type AllProductsLazyQueryHookResult = ReturnType<typeof useAllProductsLazyQuery>;
export type AllProductsQueryResult = Apollo.QueryResult<AllProductsQuery, AllProductsQueryVariables>;
export const AllUsersDocument = gql`
query allUsers {
allUsers {
id
firstName
lastName
profile {
id
balance
image
lastPurchaseDate
}
}
}
`;
export type CreateOrderMutation = { __typename?: 'Mutation', createOrder: { __typename?: 'CreateOrderSuccess', order: { __typename?: 'Order', id: string, orderSum: number, customer?: { __typename?: 'User', id: string } | null | undefined } } | { __typename?: 'FormErrors', error: boolean, message: string, fields: Array<{ __typename?: 'FieldError', field: string, message: string }> } | { __typename?: 'InsufficientFunds', error: boolean, message: string, amountLacking: number } };
/**
* __useAllUsersQuery__
*
* To run a query within a React component, call `useAllUsersQuery` and pass it any options that fit your needs.
* When your component renders, `useAllUsersQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useAllUsersQuery({
* variables: {
* },
* });
*/
export function useAllUsersQuery(baseOptions?: Apollo.QueryHookOptions<AllUsersQuery, AllUsersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<AllUsersQuery, AllUsersQueryVariables>(AllUsersDocument, options);
}
export function useAllUsersLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<AllUsersQuery, AllUsersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<AllUsersQuery, AllUsersQueryVariables>(AllUsersDocument, options);
}
export type AllUsersQueryHookResult = ReturnType<typeof useAllUsersQuery>;
export type AllUsersLazyQueryHookResult = ReturnType<typeof useAllUsersLazyQuery>;
export type AllUsersQueryResult = Apollo.QueryResult<AllUsersQuery, AllUsersQueryVariables>;
export const AllProductsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"allProducts"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"active"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"allProducts"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"filters"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"active"},"value":{"kind":"Variable","name":{"kind":"Name","value":"active"}}}]}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"imageUrl"}},{"kind":"Field","name":{"kind":"Name","value":"salePriceExt"}},{"kind":"Field","name":{"kind":"Name","value":"salePriceInt"}}]}}]}}]} as unknown as DocumentNode<AllProductsQuery, AllProductsQueryVariables>;
export const AllUsersDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"allUsers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"allUsers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"profile"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"balance"}},{"kind":"Field","name":{"kind":"Name","value":"image"}},{"kind":"Field","name":{"kind":"Name","value":"lastPurchaseDate"}}]}}]}}]}}]} as unknown as DocumentNode<AllUsersQuery, AllUsersQueryVariables>;
export const CreateOrderDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateOrder"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"customerId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"orderLines"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"OrderLineInput"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createOrder"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"customerId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"customerId"}}},{"kind":"Argument","name":{"kind":"Name","value":"orderLines"},"value":{"kind":"Variable","name":{"kind":"Name","value":"orderLines"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CreateOrderSuccess"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"order"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"customer"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}},{"kind":"Field","name":{"kind":"Name","value":"orderSum"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"InsufficientFunds"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"error"}},{"kind":"Field","name":{"kind":"Name","value":"message"}},{"kind":"Field","name":{"kind":"Name","value":"amountLacking"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FormErrors"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"error"}},{"kind":"Field","name":{"kind":"Name","value":"message"}},{"kind":"Field","name":{"kind":"Name","value":"fields"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"field"}},{"kind":"Field","name":{"kind":"Name","value":"message"}}]}}]}}]}}]}}]} as unknown as DocumentNode<CreateOrderMutation, CreateOrderMutationVariables>;