Sure! Here's an example onSubmit function in React that sends form data to a GraphQL API using the apollo-client library:
javascript Copy code
import React, { useState } from 'react';
import { useMutation } from '@apollo/client';
import { ADD_DATA_MUTATION } from './graphql/mutations';
function DataEntryForm() {
const [formData, setFormData] = useState({});
const [addData, { loading, error }] = useMutation(ADD_DATA_MUTATION);
const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevFormData) => ({ ...prevFormData, [name]: value }));
};
const handleSubmit = async (event) => {
event.preventDefault();
try {
await addData({ variables: { input: formData } });
// Handle successful submission
} catch (error) {
// Handle submission errors
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" name="name" onChange={handleChange} />
</label>
<label>
Email:
<input type="email" name="email" onChange={handleChange} />
</label>
<button type="submit">Submit</button>
{loading && <p>Loading...</p>}
{error && <p>Error: {error.message}</p>}
</form>
);
}
In this example, we're using the useMutation hook from @apollo/client to define a GraphQL mutation operation that will send the form data to the API. We define the mutation in a separate file (graphql/mutations.js) and import it into this component.
When the form is submitted, we call the addData mutation function with the formData as the input variable. The try/catch block handles any errors that might occur during the submission process.
The loading and error states are used to show a message to the user while the submission is in progress, or if there's an error with the submission.
This is just an example, so you'll need to replace ADD_DATA_MUTATION with your actual GraphQL mutation and update the form fields to match your data model.
use the form library react-hook-form
Sure! Here's an example onSubmit function in React that uses the react-hook-form library to manage form state and validation, and then sends the form data to a GraphQL API:
javascript Copy code
import React from 'react';
import { useForm } from 'react-hook-form';
import { useMutation } from '@apollo/client';
import { ADD_DATA_MUTATION } from './graphql/mutations';
function DataEntryForm() {
const { register, handleSubmit, errors } = useForm();
const [addData, { loading, error }] = useMutation(ADD_DATA_MUTATION);
const onSubmit = async (formData) => {
try {
await addData({ variables: { input: formData } });
// Handle successful submission
} catch (error) {
// Handle submission errors
}
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>
Name:
<input type="text" name="name" ref={register({ required: true })} />
{errors.name && <p>Name is required</p>}
</label>
<label>
Email:
<input type="email" name="email" ref={register({ required: true })} />
{errors.email && <p>Email is required</p>}
</label>
<button type="submit">Submit</button>
{loading && <p>Loading...</p>}
{error && <p>Error: {error.message}</p>}
</form>
);
}
In this example, we're using the useForm hook from react-hook-form to manage the form state and validation rules. We define the onSubmit function to handle form submission, and pass it to the handleSubmit function returned by useForm.
We use the register function to register each form input with react-hook-form and specify any validation rules for that input (in this case, required). We then use the errors object returned by useForm to display error messages for any fields that fail validation.
When the form is submitted, we call the addData mutation function with the formData object as the input variable. The try/catch block handles any errors that might occur during the submission process.
The loading and error states are used to show a message to the user while the submission is in progress, or if there's an error with the submission.
This is just an example, so you'll need to replace ADD_DATA_MUTATION with your actual GraphQL mutation and update the form fields to match your data model. You may also need to adjust the validation rules to fit your requirements.
now use typescript and assign default values to the form fields
Sure! Here's an example of how you can use TypeScript to define the form data interface, set default values for the form fields, and integrate it with react-hook-form and a GraphQL API:
typescript Copy code
import React from 'react';
import { useForm } from 'react-hook-form';
import { useMutation } from '@apollo/client';
import { ADD_DATA_MUTATION } from './graphql/mutations';
interface FormData {
name: string;
email: string;
}
const defaultValues: FormData = {
name: '',
email: '',
};
function DataEntryForm() {
const { register, handleSubmit, errors } = useForm<FormData>({ defaultValues });
const [addData, { loading, error }] = useMutation(ADD_DATA_MUTATION);
const onSubmit = async (formData: FormData) => {
try {
await addData({ variables: { input: formData } });
// Handle successful submission
} catch (error) {
// Handle submission errors
}
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>
Name:
<input type="text" name="name" ref={register({ required: true })} />
{errors.name && <p>Name is required</p>}
</label>
<label>
Email:
<input type="email" name="email" ref={register({ required: true })} />
{errors.email && <p>Email is required</p>}
</label>
<button type="submit">Submit</button>
{loading && <p>Loading...</p>}
{error && <p>Error: {error.message}</p>}
</form>
);
}
In this example, we define the FormData interface to specify the shape of the form data. We also define defaultValues for the form fields.
We use the useForm hook with FormData as the generic type argument and pass defaultValues as an option. We then use the register function to register each form input with react-hook-form and specify any validation rules for that input (in this case, required). We use the errors object returned by useForm to display error messages for any fields that fail validation.
When the form is submitted, we call the addData mutation function with the formData object as the input variable. The try/catch block handles any errors that might occur during the submission process.
The loading and error states are used to show a message to the user while the submission is in progress, or if there's an error with the submission.
This is just an example, so you'll need to replace ADD_DATA_MUTATION with your actual GraphQL mutation and update the form fields to match your data model. You may also need to adjust the validation rules to fit your requirements.
now refactor the form inputs to a hook that uses material ui Textfield and autocomplete components
Sure! Here's an example of how you can refactor the form inputs to a custom hook that uses Material UI's TextField and Autocomplete components:
typescript Copy code
import React from 'react';
import { useForm } from 'react-hook-form';
import { useMutation } from '@apollo/client';
import { ADD_DATA_MUTATION } from './graphql/mutations';
import { TextField, Autocomplete } from '@material-ui/core';
interface Option {
value: string;
label: string;
}
interface FormValues {
name: string;
email: string;
city: Option | null;
}
const defaultValues: FormValues = {
name: '',
email: '',
city: null,
};
const cities: Option[] = [
{ value: 'london', label: 'London' },
{ value: 'paris', label: 'Paris' },
{ value: 'new-york', label: 'New York' },
{ value: 'sydney', label: 'Sydney' },
];
interface Props {
onSubmit: (values: FormValues) => Promise<void>;
}
function DataEntryForm({ onSubmit }: Props) {
const { register, handleSubmit, errors, setValue } = useForm<FormValues>({ defaultValues });
const [addData, { loading, error }] = useMutation(ADD_DATA_MUTATION);
const handleCityChange = (_: React.ChangeEvent<{}>, value: Option | null) => {
setValue('city', value);
};
const renderCityOption = (option: Option) => {
return (
<React.Fragment>
<span>{option.label}</span>
</React.Fragment>
);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
name="name"
label="Name"
inputRef={register({ required: true })}
error={!!errors.name}
helperText={errors.name ? 'Name is required' : ''}
/>
<TextField
name="email"
label="Email"
type="email"
inputRef={register({ required: true })}
error={!!errors.email}
helperText={errors.email ? 'Email is required' : ''}
/>
<Autocomplete
name="city"
options={cities}
getOptionLabel={(option) => option.label}
renderOption={renderCityOption}
onChange={handleCityChange}
value={defaultValues.city}
renderInput={(params) => (
<TextField
{...params}
label="City"
inputRef={register({ required: true })}
error={!!errors.city}
helperText={errors.city ? 'City is required' : ''}
/>
)}
/>
<button type="submit">Submit</button>
{loading && <p>Loading...</p>}
{error && <p>Error: {error.message}</p>}
</form>
);
}
now add a field array to the form
Sure, I can help you with that. Here's an example of how you can add a field array to the form using react-hook-form and Material UI components:
css Copy code
)}
{error && <p>Error: {error.message}</p>}
</form>
);
}
export default DataEntryForm;
vbnet Copy code
In this example, we added a `tags` field to the `FormValues` interface and assigned an empty string array as the default value. We then used the `useFieldArray` hook from `react-hook-form` to manage the state of the tags field array.
We mapped over the `fields` array returned from `useFieldArray` to render each individual `TextField` for the tags. We also included a `Button` to add a new tag to the field array and a `Button` to remove a specific tag.
Note that we used the `defaultValue` prop on the `TextField` component to set the default value for each tag input field.
I hope this helps! Let me know if you have any questions.
now include a file upload field in the form and upload the files to an azure storage account container
Sure, I can help you with that. Here's an example of how you can add a file upload field to the form and upload the files to an Azure Storage Account Container using react-hook-form and Azure Blob Storage SDK:
typescript Copy code
? 'Please enter a name'
: ''}
/>
<TextField
name="email"
label="Email"
inputRef={register({ required: true })}
error={!!errors.email}
helperText={errors.email ? 'Please enter an email' : ''}
/>
<Autocomplete
name="city"
options={cities}
getOptionLabel={(option) => option.label}
renderOption={renderCityOption}
onChange={handleCityChange}
value={getValue('city', null)}
renderInput={(params) => (
<TextField {...params} label="City" variant="outlined" inputRef={register({ required: true })} />
)}
/>
{fields.map((field, index) => (
<div key={field.id}>
<TextField
name={`tags[${index}]`}
label="Tag"
defaultValue={field.value}
inputRef={register()}
/>
<Button type="button" onClick={() => remove(index)}>
Remove Tag
</Button>
</div>
))}
<Button type="button" onClick={() => append('')}>
Add Tag
</Button>
<input type="file" name="files" onChange={handleFileChange} ref={register()} />
{loading && <LinearProgress variant="determinate" value={uploadProgress} />}
<Button type="submit" disabled={loading}>
Submit
</Button>
{error && <p>Error: {error.message}</p>}
</form>
);
}
export default DataEntryForm;
typescript Copy code
In this example, we added an input of type `file` to the form using the `TextField` component. We then added an `onChange` event handler to capture the selected file(s) and set the state using the `setValue` function from `react-hook-form`.
We created a new function `uploadFilesToBlobStorage` to upload the selected files to an Azure Storage Account Container using the `BlobServiceClient` from the `@azure/storage-blob` package. We also added a `LinearProgress` component to display the upload progress while the files are being uploaded.
In the `onSubmitForm` function, we first check if there are any files selected and call the `uploadFilesToBlobStorage` function to upload the files. We then call the `onSubmit` function passed in as a prop to submit the rest of the form data to the GraphQL API.
I hope this helps you with your project! Let me know if you have any questions.
Sure! I'll update the code to use React Recoil for state management. Here's the updated code:
php Copy code
</div>
))}
<Button
type="button"
onClick={() =>
setFormData((prev) => ({
...prev,
tags: [...formData.tags, ''],
}))
}
>
Add Tag
</Button>
<Controller
name="files"
control={control}
as={<input type="file" ref={register()} onChange={handleFileChange} />}
/>
{loading && <LinearProgress variant="determinate" value={uploadProgress} />}
<Button type="submit" disabled={loading}>
Submit
</Button>
{error && <p>Error: {error.message}</p>}
</form>
);
}
export default DataEntryForm;
vbnet Copy code
In this updated version, we're using React Recoil to manage the form state. We created an atom called `dataEntryFormState` that holds the form data. We use `useRecoilState` to get and set the form data state.
We also updated the form fields to use `Controller` components from `react-hook-form` to link the fields to the `dataEntryFormState` atom. We updated the `handleCityChange` and `handleFileChange` functions to use the `setFormData` function to update the `dataEntryFormState` atom.
In the `onSubmitForm` function, we set the `loading` state to true to show a progress bar while the form is submitting. If files were selected, we call the `uploadFileToBlobStorage` function to upload the files to the Azure Storage Account Container. We update the `dataEntryFormState` atom with the `urls` of the uploaded files. If an error occurs during file upload, we set the `error` state to display the error message.
I hope this helps you with your project. Let me know if you have any questions!
Sure, I can help you with that. Here's an updated version of the form that saves the data to Azure Cosmos DB:
typescript Copy code
<TextField {...params} label="City" />
}
rules={{ required: true }}
onChange={([, value]) => setFormData((prev) => ({ ...prev, city: value }))}
value={getValue('city', null)}
/>
{formData.tags.map((tag, index) => (
<div key={index}>
<Controller
name={`tags[${index}]`}
control={control}
defaultValue={tag}
as={<TextField label="Tag" />}
/>
<Button
type="button"
onClick={() =>
setFormData((prev) => ({
...prev,
tags: formData.tags.filter((_, i) => i !== index),
}))
}
>
Remove Tag
</Button>
</div>
))}
<Button
type="button"
onClick={() =>
setFormData((prev) => ({
...prev,
tags: [...formData.tags, ''],
}))
}
>
Add Tag
</Button>
<Controller
name="files"
control={control}
as={<input type="file" ref={register()} onChange={handleFileChange} />}
/>
{loading && <LinearProgress variant="determinate" value={uploadProgress} />}
<Button type="submit" disabled={loading}>
Submit
</Button>
{error && <p>Error: {error.message}</p>}
</form>
);
}
export default DataEntryForm;
vbnet Copy code
In this updated version, we use the `@azure/cosmos` package to connect to an Azure Cosmos DB account and save the data to a container.
We use the `CosmosClient` to connect to the Azure Cosmos DB account, and then we get a reference to the database and container where we want to save the data. We then use the `create` method of the `items` object to create a new item in the container.
We pass the form data to the `onSubmit` function to notify the parent component that the form was submitted successfully.
I hope this helps you with your project! Let me know if you have any questions.
use a field array for tags like you did before
Sure, here's an updated version of the form that includes a field array for tags and saves the data to Azure Cosmos DB:
typescript Copy code
options={cities}
getOptionLabel={(option) => option.label}
renderOption={(option) => <>{option.label}</>}
renderInput={(params) => <TextField {...params} label="City" />}
}
rules={{ required: true }}
onChange={([, value]) => setFormData((prev) => ({ ...prev, city: value }))}
value={getValue('city', null)}
/>
{fields.map((tag, index) => (
<div key={tag.id}>
<Controller
name={`tags[${index}].value`}
control={control}
defaultValue={tag.value}
as={<TextField label="Tag" />}
/>
<Button type="button" onClick={() => remove(index)}>
Remove Tag
</Button>
</div>
))}
<Button type="button" onClick={() => append({ value: '' })}>
Add Tag
</Button>
<Controller
name="files"
control={control}
as={<input type="file" ref={register()} onChange={handleFileChange} />}
/>
{loading && <LinearProgress variant="determinate" value={uploadProgress} />}
<Button type="submit" disabled={loading}>
Submit
</Button>
{error && <p>Error: {error.message}</p>}
</form>
);
}
export default DataEntryForm;
perl Copy code
In this updated version, we use the `useFieldArray` hook from `react-hook-form` to manage the `tags` field array. We use the `fields` array to render the tag fields, and we use the `append` and `remove` functions to add and remove tag fields.
We map the `tags` array to an array of tag values before saving the data to Cosmos DB.
I hope this helps you with your project! Let me know if you have any questions.
can you make the render function less verbose?
Yes, we can use the ES6 destructuring syntax to make the render function less verbose. Here's the updated version:
typescript Copy code
options={cities}
getOptionLabel={(option) => option.label}
renderOption={(option) => <>{option.label}</>}
renderInput={(params) => <TextField {...params} label="City" />}
}
rules={{ required: true }}
onChange={([, value]) => setFormData((prev) => ({ ...prev, city: value }))}
value={city}
/>
{fields.map((tag, index) => (
<div key={tag.id}>
<Controller
name={`tags[${index}].value`}
control={control}
defaultValue={tag.value}
as={<TextField label="Tag" />}
/>
<Button type="button" onClick={() => remove(index)}>
Remove Tag
</Button>
</div>
))}
<Button type="button" onClick={() => append({ value: '' })}>
Add Tag
</Button>
<Controller
name="files"
control={control}
as={<input type="file" ref={register()} onChange={handleFileChange} />}
/>
{loading && <LinearProgress variant="determinate" value={uploadProgress} />}
<Button type="submit" disabled={loading}>
Submit
</Button>
{error && <p>Error: {error.message}</p>}
</form>
);
}
export default DataEntryForm;
typescript Copy code
In this updated version, we use the destructuring syntax to extract the `name`, `email`, `city`, `tags`, and `files` properties from the `formData` object.
I hope this helps you with your project! Let me know if you have any questions.
make sure the tag field is unmounted when the remove tag button is clicked
Good catch! When the "Remove Tag" button is clicked, we should also unmount the corresponding tag field. To do this, we can call the remove function of the useFieldArray hook with the index of the tag that we want to remove. Here's the updated version of the form:
php Copy code
helperText={errors.email ? 'Please enter an email' : ''}
/>
<Controller
name="city"
control={control}
as={
<Autocomplete
options={cities}
getOptionLabel={(option) => option.label}
renderOption={(option) => <>{option.label}</>}
renderInput={(params) => <TextField {...params} label="City" />}
}
rules={{ required: true }}
onChange={([, value]) => setFormData((prev) => ({ ...prev, city: value }))}
value={city}
/>
{fields.map((tag, index) => (
<div key={tag.id}>
<Controller
name={`tags[${index}].value`}
control={control}
defaultValue={tag.value}
as={<TextField label="Tag" />}
/>
<Button type="button" onClick={() => remove(index)}>
Remove Tag
</Button>
{index === fields.length - 1 && (
<Button type="button" onClick={() => append({ value: '' })}>
Add Tag
</Button>
)}
</div>
))}
<Controller
name="files"
control={control}
as={<input type="file" ref={register()} onChange={handleFileChange} />}
/>
{loading && <LinearProgress variant="determinate" value={uploadProgress} />}
<Button type="submit" disabled={loading}>
Submit
</Button>
{error && <p>Error: {error.message}</p>}
</form>
);
}
export default DataEntryForm;
sql Copy code
In this updated version, we check if the tag is the last one in the `fields` array and only show the "Add Tag" button for the last tag. This ensures that we don't add an extra tag field when the form is submitted.
I hope this helps you with your project! Let me know if you have any questions.
now wrap the form input fields in a styled card component
Sure, we can wrap the form input fields in a styled card component to improve the layout and visual presentation of the form. Here's an updated version of the form with the card component:
php Copy code
/>
<Controller
name="city"
control={control}
as={
<Autocomplete
options={cities}
getOptionLabel={(option) => option.label}
renderOption={(option) => <>{option.label}</>}
renderInput={(params) => <TextField {...params} label="City" />}
}
rules={{ required: true }}
onChange={([, value]) => setFormData((prev) => ({ ...prev, city: value }))}
value={city}
/>
{fields.map((tag, index) => (
<div key={tag.id}>
<Controller
name={`tags[${index}].value`}
control={control}
defaultValue={tag.value}
as={<TextField label="Tag" />}
/>
<Button type="button" onClick={() => remove(index)}>
Remove Tag
</Button>
{index === fields.length - 1 && (
<Button type="button" onClick={() => append({ value: '' })}>
Add Tag
</Button>
)}
</div>
))}
<Controller
name="files"
control={control}
as={<input type="file" ref={register()} onChange={handleFileChange} />}
/>
{loading && <LinearProgress variant="determinate" value={uploadProgress} />}
<CardActions>
<Button type="submit" disabled={loading}>
Submit
</Button>
</CardActions>
{error && <p>Error: {error.message}</p>}
</form>
</CardContent>
</Card>
);
}
export default DataEntryForm;
css Copy code
In this updated version, we wrap the form fields in a `Card` component and use the `CardContent` and `CardActions` components to group the form fields and submit button together. This gives the form a more organized and visually appealing layout.
I hope this helps you with your project! Let me know if you have any questions.
refactor the tags field to its own functional component hook
Sure, we can refactor the tags field to its own functional component hook to make the code more modular and reusable. Here's one way to do it:
javascript Copy code
import React from 'react';
import { useFieldArray } from 'react-hook-form';
import { TextField, Button } from '@material-ui/core';
function TagsField({ control }) {
const { fields, append, remove } = useFieldArray({ control, name: 'tags' });
return (
<>
{fields.map((tag, index) => (
<div key={tag.id}>
<TextField
name={`tags[${index}].value`}
inputRef={control.register()}
defaultValue={tag.value}
label="Tag"
/>
<Button type="button" onClick={() => remove(index)}>
Remove Tag
</Button>
{index === fields.length - 1 && (
<Button type="button" onClick={() => append({ value: '' })}>
Add Tag
</Button>
)}
</div>
))}
</>
);
}
export default TagsField;
In this TagsField component, we pass the control object from the parent form as a prop to the useFieldArray hook to manage the tags field array. We use the fields array returned by the useFieldArray hook to render the TextField and Button components for each tag. We also conditionally render the "Add Tag" button for the last tag field.
We can then use the TagsField component in the DataEntryForm component like this:
vbnet Copy code
try {
const client = new CosmosClient({
endpoint: process.env.REACT_APP_COSMOSDB_ENDPOINT,
key: process.env.REACT_APP_COSMOSDB_KEY,
});
const database = client.database(process.env.REACT_APP_COSMOSDB_DATABASE);
const container = database.container(process.env.REACT_APP_COSMOSDB_CONTAINER);
const response = await container.items.create({
name: data.name,
email: data.email,
city: data.city?.label,
tags: data.tags.map((tag) => tag.value),
urls: formData.urls,
});
onSubmit(data);
} catch (error) {
console.error(error);
setError(error);
}
setLoading(false);
};
return (
export default DataEntryForm;
typescript Copy code
In this updated version, we import the `TagsField` component and pass the `control` object from the parent form as a prop. We render the `TagsField` component to display the tags field array.
This approach makes the code more modular and reusable, since we can use the `TagsField` component in other forms that require a tags field array.
I hope this helps you with your project! Let me know if you have any questions.
include a a component that displays a list of the file names for each form submitted
Sure, we can include a component that displays a list of file names for each form submitted. Here's one way to do it:
csharp Copy code
rules={{ required: true }}
as={<TextField label="Email" />}
error={!!errors.email}
helperText={errors.email ? 'Please enter an email' : ''}
/>
<Controller
name="city"
control={control}
as={
<Autocomplete
options={cities}
Dataset releases Not yet included in a published release.
In this example, we define a custom hook called useFormInputs that returns a TextField or Autocomplete component depending on the input type. We also define an Option interface to specify the shape of the cities array, and a FormValues interface to specify the shape of the form data.
We use the TextField component to render the name and email inputs. We pass the inputRef from register as a prop to each TextField, and use the error and helperText props to display error messages if the inputs fail validation.
We use the Autocomplete component to render the city input. We pass the options array and the getOptionLabel
import React from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { useMutation } from '@apollo/client';
import { ADD_DATA_MUTATION } from './graphql/mutations';
import { TextField, Autocomplete, Button } from '@material-ui/core';
interface Option {
value: string;
label: string;
}
interface FormValues {
name: string;
email: string;
city: Option | null;
tags: string[];
}
const defaultValues: FormValues = {
name: '',
email: '',
city: null,
tags: [],
};
const cities: Option[] = [
{ value: 'london', label: 'London' },
{ value: 'paris', label: 'Paris' },
{ value: 'new-york', label: 'New York' },
{ value: 'sydney', label: 'Sydney' },
];
interface Props {
onSubmit: (values: FormValues) => Promise<void>;
}
function DataEntryForm({ onSubmit }: Props) {
const { register, handleSubmit, errors, setValue, control } = useForm<FormValues>({ defaultValues });
const { fields, append, remove } = useFieldArray({
control,
name: 'tags',
});
const [addData, { loading, error }] = useMutation(ADD_DATA_MUTATION);
const handleCityChange = (_: React.ChangeEvent<{}>, value: Option | null) => {
setValue('city', value);
};
const renderCityOption = (option: Option) => {
return (
<React.Fragment>
<span>{option.label}</span>
</React.Fragment>
);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
name="name"
label="Name"
inputRef={register({ required: true })}
error={!!errors.name}
helperText={errors.name ? 'Name is required' : ''}
/>
<TextField
name="email"
label="Email"
type="email"
inputRef={register({ required: true })}
error={!!errors.email}
helperText={errors.email ? 'Email is required' : ''}
/>
<Autocomplete
name="city"
options={cities}
getOptionLabel={(option) => option.label}
renderOption={renderCityOption}
onChange={handleCityChange}
value={defaultValues.city}
renderInput={(params) => (
<TextField
{...params}
label="City"
inputRef={register({ required: true })}
error={!!errors.city}
helperText={errors.city ? 'City is required' : ''}
/>
)}
/>
<div>
<label>Tags:</label>
{fields.map((field, index) => (
<div key={field.id}>
<TextField
name={`tags[${index}]`}
inputRef={register({ required: true })}
defaultValue={field.value}
variant="outlined"
size="small"
margin="dense"
fullWidth
placeholder="Tag"
/>
<Button type="button" onClick={() => remove(index)}>
Remove
</Button>
</div>
))}
<Button type="button" onClick={() => append('')}>
Add Tag
</Button>
</div>
<Button type="submit">Submit</Button>
{loading && <p>Loading...</p
import React, { useState } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { useMutation } from '@apollo/client';
import { ADD_DATA_MUTATION } from './graphql/mutations';
import { TextField, Autocomplete, Button, LinearProgress } from '@material-ui/core';
import { BlobServiceClient } from '@azure/storage-blob';
interface Option {
value: string;
label: string;
}
interface FormValues {
name: string;
email: string;
city: Option | null;
tags: string[];
files: FileList | null;
}
const defaultValues: FormValues = {
name: '',
email: '',
city: null,
tags: [],
files: null,
};
const cities: Option[] = [
{ value: 'london', label: 'London' },
{ value: 'paris', label: 'Paris' },
{ value: 'new-york', label: 'New York' },
{ value: 'sydney', label: 'Sydney' },
];
interface Props {
onSubmit: (values: FormValues) => Promise<void>;
}
function DataEntryForm({ onSubmit }: Props) {
const { register, handleSubmit, errors, setValue, control } = useForm<FormValues>({ defaultValues });
const { fields, append, remove } = useFieldArray({
control,
name: 'tags',
});
const [addData, { loading, error }] = useMutation(ADD_DATA_MUTATION);
const [uploadProgress, setUploadProgress] = useState(0);
const handleCityChange = (_: React.ChangeEvent<{}>, value: Option | null) => {
setValue('city', value);
};
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = event.target.files;
setValue('files', files);
};
const uploadFilesToBlobStorage = async (files: FileList) => {
const blobServiceClient = new BlobServiceClient(process.env.REACT_APP_AZURE_STORAGE_CONNECTION_STRING);
const containerClient = blobServiceClient.getContainerClient(process.env.REACT_APP_AZURE_STORAGE_CONTAINER_NAME);
for (let i = 0; i < files.length; i++) {
const file = files[i];
const blockBlobClient = containerClient.getBlockBlobClient(file.name);
await blockBlobClient.uploadBrowserData(file, {
blockSize: 4 * 1024 * 1024, // 4MB block size
onProgress: (ev) => {
const progress = Math.round((ev.loadedBytes / ev.totalBytes) * 100);
setUploadProgress(progress);
},
});
}
};
const onSubmitForm = async (values: FormValues) => {
try {
if (values.files) {
await uploadFilesToBlobStorage(values.files);
}
await onSubmit(values);
} catch (error) {
console.error(error);
}
};
const renderCityOption = (option: Option) => {
return (
<React.Fragment>
<span>{option.label}</span>
</React.Fragment>
);
};
return (
<form onSubmit={handleSubmit(onSubmitForm)}>
<TextField
name="name"
label="Name"
inputRef={register({ required: true })}
error={!!errors.name}
helperText={errors.name
import React, { useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { TextField, Button, LinearProgress, Autocomplete } from '@material-ui/core';
import { useRecoilState } from 'recoil';
import { dataEntryFormState } from './dataEntryFormState';
import { uploadFileToBlobStorage } from './azureStorage';
const cities = [
{ label: 'New York', value: 'NY' },
{ label: 'San Francisco', value: 'SF' },
{ label: 'Los Angeles', value: 'LA' },
{ label: 'Chicago', value: 'CHI' },
];
function DataEntryForm({ onSubmit }) {
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [error, setError] = useState(null);
const { control, handleSubmit, register, errors } = useForm({
defaultValues: {
name: '',
email: '',
city: null,
tags: [''],
files: null,
},
});
const [formData, setFormData] = useRecoilState(dataEntryFormState);
const getValue = (name, defaultValue) => formData[name] || defaultValue;
const handleCityChange = (event, value) => {
setFormData((prev) => ({ ...prev, city: value }));
};
const handleFileChange = (event) => {
setFormData((prev) => ({ ...prev, files: event.target.files }));
};
const onSubmitForm = async (data) => {
setLoading(true);
if (data.files) {
try {
const urls = await uploadFileToBlobStorage(data.files, setUploadProgress);
setFormData((prev) => ({ ...prev, urls }));
} catch (e) {
setError(e);
setLoading(false);
return;
}
}
onSubmit(data);
setLoading(false);
};
return (
<form onSubmit={handleSubmit(onSubmitForm)}>
<Controller
name="name"
control={control}
rules={{ required: true }}
as={<TextField label="Name" />}
error={!!errors.name}
helperText={errors.name ? 'Please enter a name' : ''}
/>
<Controller
name="email"
control={control}
rules={{ required: true }}
as={<TextField label="Email" />}
error={!!errors.email}
helperText={errors.email ? 'Please enter an email' : ''}
/>
<Controller
name="city"
control={control}
as={
<Autocomplete
options={cities}
getOptionLabel={(option) => option.label}
renderOption={(option) => <>{option.label}</>}
renderInput={(params) => <TextField {...params} label="City" />}
/>
}
rules={{ required: true }}
onChange={([, value]) => setFormData((prev) => ({ ...prev, city: value }))}
value={getValue('city', null)}
/>
{formData.tags.map((tag, index) => (
<div key={index}>
<Controller
name={`tags[${index}]`}
control={control}
defaultValue={tag}
as={<TextField label="Tag" />}
/>
<Button type="button" onClick={() => setFormData((prev) => ({ ...prev, tags: formData.tags.filter((_, i) => i !== index) }))}>
Remove Tag
</Button>
import React, { useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { TextField, Button, LinearProgress, Autocomplete } from '@material-ui/core';
import { useRecoilState } from 'recoil';
import { dataEntryFormState } from './dataEntryFormState';
import { uploadFileToBlobStorage } from './azureStorage';
import { CosmosClient } from '@azure/cosmos';
const cities = [
{ label: 'New York', value: 'NY' },
{ label: 'San Francisco', value: 'SF' },
{ label: 'Los Angeles', value: 'LA' },
{ label: 'Chicago', value: 'CHI' },
];
function DataEntryForm({ onSubmit }) {
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [error, setError] = useState(null);
const { control, handleSubmit, register, errors } = useForm({
defaultValues: {
name: '',
email: '',
city: null,
tags: [''],
files: null,
},
});
const [formData, setFormData] = useRecoilState(dataEntryFormState);
const getValue = (name, defaultValue) => formData[name] || defaultValue;
const handleCityChange = (event, value) => {
setFormData((prev) => ({ ...prev, city: value }));
};
const handleFileChange = (event) => {
setFormData((prev) => ({ ...prev, files: event.target.files }));
};
const onSubmitForm = async (data) => {
setLoading(true);
if (data.files) {
try {
const urls = await uploadFileToBlobStorage(data.files, setUploadProgress);
setFormData((prev) => ({ ...prev, urls }));
} catch (e) {
setError(e);
setLoading(false);
return;
}
}
try {
const client = new CosmosClient({
endpoint: process.env.REACT_APP_COSMOSDB_ENDPOINT,
key: process.env.REACT_APP_COSMOSDB_KEY,
});
const database = client.database(process.env.REACT_APP_COSMOSDB_DATABASE);
const container = database.container(process.env.REACT_APP_COSMOSDB_CONTAINER);
const response = await container.items.create({
name: data.name,
email: data.email,
city: data.city?.label,
tags: data.tags,
urls: formData.urls,
});
onSubmit(data);
} catch (error) {
console.error(error);
setError(error);
}
setLoading(false);
};
return (
<form onSubmit={handleSubmit(onSubmitForm)}>
<Controller
name="name"
control={control}
rules={{ required: true }}
as={<TextField label="Name" />}
error={!!errors.name}
helperText={errors.name ? 'Please enter a name' : ''}
/>
<Controller
name="email"
control={control}
rules={{ required: true }}
as={<TextField label="Email" />}
error={!!errors.email}
helperText={errors.email ? 'Please enter an email' : ''}
/>
<Controller
name="city"
control={control}
as={
<Autocomplete
options={cities}
getOptionLabel={(option) => option.label}
renderOption={(option) => <>{option.label}</>}
renderInput={(params) =>
import React, { useState } from 'react';
import { useForm, Controller, useFieldArray } from 'react-hook-form';
import { TextField, Button, LinearProgress, Autocomplete } from '@material-ui/core';
import { useRecoilState } from 'recoil';
import { dataEntryFormState } from './dataEntryFormState';
import { uploadFileToBlobStorage } from './azureStorage';
import { CosmosClient } from '@azure/cosmos';
const cities = [
{ label: 'New York', value: 'NY' },
{ label: 'San Francisco', value: 'SF' },
{ label: 'Los Angeles', value: 'LA' },
{ label: 'Chicago', value: 'CHI' },
];
function DataEntryForm({ onSubmit }) {
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [error, setError] = useState(null);
const { control, handleSubmit, register, errors } = useForm({
defaultValues: {
name: '',
email: '',
city: null,
tags: [{ value: '' }],
files: null,
},
});
const [formData, setFormData] = useRecoilState(dataEntryFormState);
const { fields, append, remove } = useFieldArray({ control, name: 'tags' });
const getValue = (name, defaultValue) => formData[name] || defaultValue;
const handleCityChange = (event, value) => {
setFormData((prev) => ({ ...prev, city: value }));
};
const handleFileChange = (event) => {
setFormData((prev) => ({ ...prev, files: event.target.files }));
};
const onSubmitForm = async (data) => {
setLoading(true);
if (data.files) {
try {
const urls = await uploadFileToBlobStorage(data.files, setUploadProgress);
setFormData((prev) => ({ ...prev, urls }));
} catch (e) {
setError(e);
setLoading(false);
return;
}
}
try {
const client = new CosmosClient({
endpoint: process.env.REACT_APP_COSMOSDB_ENDPOINT,
key: process.env.REACT_APP_COSMOSDB_KEY,
});
const database = client.database(process.env.REACT_APP_COSMOSDB_DATABASE);
const container = database.container(process.env.REACT_APP_COSMOSDB_CONTAINER);
const response = await container.items.create({
name: data.name,
email: data.email,
city: data.city?.label,
tags: data.tags.map((tag) => tag.value),
urls: formData.urls,
});
onSubmit(data);
} catch (error) {
console.error(error);
setError(error);
}
setLoading(false);
};
return (
<form onSubmit={handleSubmit(onSubmitForm)}>
<Controller
name="name"
control={control}
rules={{ required: true }}
as={<TextField label="Name" />}
error={!!errors.name}
helperText={errors.name ? 'Please enter a name' : ''}
/>
<Controller
name="email"
control={control}
rules={{ required: true }}
as={<TextField label="Email" />}
error={!!errors.email}
helperText={errors.email ? 'Please enter an email' : ''}
/>
<Controller
name="city"
control={control}
as={
<Autocomplete
import React, { useState } from 'react';
import { useForm, Controller, useFieldArray } from 'react-hook-form';
import { TextField, Button, LinearProgress, Autocomplete } from '@material-ui/core';
import { useRecoilState } from 'recoil';
import { dataEntryFormState } from './dataEntryFormState';
import { uploadFileToBlobStorage } from './azureStorage';
import { CosmosClient } from '@azure/cosmos';
const cities = [
{ label: 'New York', value: 'NY' },
{ label: 'San Francisco', value: 'SF' },
{ label: 'Los Angeles', value: 'LA' },
{ label: 'Chicago', value: 'CHI' },
];
function DataEntryForm({ onSubmit }) {
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [error, setError] = useState(null);
const { control, handleSubmit, register, errors } = useForm({
defaultValues: {
name: '',
email: '',
city: null,
tags: [{ value: '' }],
files: null,
},
});
const [formData, setFormData] = useRecoilState(dataEntryFormState);
const { fields, append, remove } = useFieldArray({ control, name: 'tags' });
const { name, email, city, tags, files } = formData;
const handleCityChange = (event, value) => {
setFormData((prev) => ({ ...prev, city: value }));
};
const handleFileChange = (event) => {
setFormData((prev) => ({ ...prev, files: event.target.files }));
};
const onSubmitForm = async (data) => {
setLoading(true);
if (data.files) {
try {
const urls = await uploadFileToBlobStorage(data.files, setUploadProgress);
setFormData((prev) => ({ ...prev, urls }));
} catch (e) {
setError(e);
setLoading(false);
return;
}
}
try {
const client = new CosmosClient({
endpoint: process.env.REACT_APP_COSMOSDB_ENDPOINT,
key: process.env.REACT_APP_COSMOSDB_KEY,
});
const database = client.database(process.env.REACT_APP_COSMOSDB_DATABASE);
const container = database.container(process.env.REACT_APP_COSMOSDB_CONTAINER);
const response = await container.items.create({
name: data.name,
email: data.email,
city: data.city?.label,
tags: data.tags.map((tag) => tag.value),
urls: formData.urls,
});
onSubmit(data);
} catch (error) {
console.error(error);
setError(error);
}
setLoading(false);
};
return (
<form onSubmit={handleSubmit(onSubmitForm)}>
<Controller
name="name"
control={control}
rules={{ required: true }}
as={<TextField label="Name" />}
error={!!errors.name}
helperText={errors.name ? 'Please enter a name' : ''}
/>
<Controller
name="email"
control={control}
rules={{ required: true }}
as={<TextField label="Email" />}
error={!!errors.email}
helperText={errors.email ? 'Please enter an email' : ''}
/>
<Controller
name="city"
control={control}
as={
<Autocomplete
import React, { useState } from 'react';
import { useForm, Controller, useFieldArray } from 'react-hook-form';
import { TextField, Button, LinearProgress, Autocomplete } from '@material-ui/core';
import { useRecoilState } from 'recoil';
import { dataEntryFormState } from './dataEntryFormState';
import { uploadFileToBlobStorage } from './azureStorage';
import { CosmosClient } from '@azure/cosmos';
const cities = [
{ label: 'New York', value: 'NY' },
{ label: 'San Francisco', value: 'SF' },
{ label: 'Los Angeles', value: 'LA' },
{ label: 'Chicago', value: 'CHI' },
];
function DataEntryForm({ onSubmit }) {
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [error, setError] = useState(null);
const { control, handleSubmit, register, errors } = useForm({
defaultValues: {
name: '',
email: '',
city: null,
tags: [{ value: '' }],
files: null,
},
});
const [formData, setFormData] = useRecoilState(dataEntryFormState);
const { fields, append, remove } = useFieldArray({ control, name: 'tags' });
const { name, email, city, tags, files } = formData;
const handleCityChange = (event, value) => {
setFormData((prev) => ({ ...prev, city: value }));
};
const handleFileChange = (event) => {
setFormData((prev) => ({ ...prev, files: event.target.files }));
};
const onSubmitForm = async (data) => {
setLoading(true);
if (data.files) {
try {
const urls = await uploadFileToBlobStorage(data.files, setUploadProgress);
setFormData((prev) => ({ ...prev, urls }));
} catch (e) {
setError(e);
setLoading(false);
return;
}
}
try {
const client = new CosmosClient({
endpoint: process.env.REACT_APP_COSMOSDB_ENDPOINT,
key: process.env.REACT_APP_COSMOSDB_KEY,
});
const database = client.database(process.env.REACT_APP_COSMOSDB_DATABASE);
const container = database.container(process.env.REACT_APP_COSMOSDB_CONTAINER);
const response = await container.items.create({
name: data.name,
email: data.email,
city: data.city?.label,
tags: data.tags.map((tag) => tag.value),
urls: formData.urls,
});
onSubmit(data);
} catch (error) {
console.error(error);
setError(error);
}
setLoading(false);
};
return (
<form onSubmit={handleSubmit(onSubmitForm)}>
<Controller
name="name"
control={control}
rules={{ required: true }}
as={<TextField label="Name" />}
error={!!errors.name}
helperText={errors.name ? 'Please enter a name' : ''}
/>
<Controller
name="email"
control={control}
rules={{ required: true }}
as={<TextField label="Email" />}
error={!!errors.email}
import React, { useState } from 'react';
import { useForm, Controller, useFieldArray } from 'react-hook-form';
import { TextField, Button, LinearProgress, Autocomplete, Card, CardContent, CardActions } from '@material-ui/core';
import { useRecoilState } from 'recoil';
import { dataEntryFormState } from './dataEntryFormState';
import { uploadFileToBlobStorage } from './azureStorage';
import { CosmosClient } from '@azure/cosmos';
const cities = [
{ label: 'New York', value: 'NY' },
{ label: 'San Francisco', value: 'SF' },
{ label: 'Los Angeles', value: 'LA' },
{ label: 'Chicago', value: 'CHI' },
];
function DataEntryForm({ onSubmit }) {
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [error, setError] = useState(null);
const { control, handleSubmit, register, errors } = useForm({
defaultValues: {
name: '',
email: '',
city: null,
tags: [{ value: '' }],
files: null,
},
});
const [formData, setFormData] = useRecoilState(dataEntryFormState);
const { fields, append, remove } = useFieldArray({ control, name: 'tags' });
const { name, email, city, tags, files } = formData;
const handleCityChange = (event, value) => {
setFormData((prev) => ({ ...prev, city: value }));
};
const handleFileChange = (event) => {
setFormData((prev) => ({ ...prev, files: event.target.files }));
};
const onSubmitForm = async (data) => {
setLoading(true);
if (data.files) {
try {
const urls = await uploadFileToBlobStorage(data.files, setUploadProgress);
setFormData((prev) => ({ ...prev, urls }));
} catch (e) {
setError(e);
setLoading(false);
return;
}
}
try {
const client = new CosmosClient({
endpoint: process.env.REACT_APP_COSMOSDB_ENDPOINT,
key: process.env.REACT_APP_COSMOSDB_KEY,
});
const database = client.database(process.env.REACT_APP_COSMOSDB_DATABASE);
const container = database.container(process.env.REACT_APP_COSMOSDB_CONTAINER);
const response = await container.items.create({
name: data.name,
email: data.email,
city: data.city?.label,
tags: data.tags.map((tag) => tag.value),
urls: formData.urls,
});
onSubmit(data);
} catch (error) {
console.error(error);
setError(error);
}
setLoading(false);
};
return (
<Card>
<CardContent>
<form onSubmit={handleSubmit(onSubmitForm)}>
<Controller
name="name"
control={control}
rules={{ required: true }}
as={<TextField label="Name" />}
error={!!errors.name}
helperText={errors.name ? 'Please enter a name' : ''}
/>
<Controller
name="email"
control={control}
rules={{ required: true }}
as={<TextField label="Email" />}
error={!!errors.email}
helperText={errors.email ? 'Please enter an
import React, { useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { TextField, Button, LinearProgress, Autocomplete, Card, CardContent, CardActions } from '@material-ui/core';
import { useRecoilState } from 'recoil';
import { dataEntryFormState } from './dataEntryFormState';
import { uploadFileToBlobStorage } from './azureStorage';
import { CosmosClient } from '@azure/cosmos';
import TagsField from './TagsField';
const cities = [
{ label: 'New York', value: 'NY' },
{ label: 'San Francisco', value: 'SF' },
{ label: 'Los Angeles', value: 'LA' },
{ label: 'Chicago', value: 'CHI' },
];
function DataEntryForm({ onSubmit }) {
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [error, setError] = useState(null);
const { control, handleSubmit, errors } = useForm({
defaultValues: {
name: '',
email: '',
city: null,
tags: [{ value: '' }],
files: null,
},
});
const [formData, setFormData] = useRecoilState(dataEntryFormState);
const { name, email, city, files } = formData;
const handleCityChange = (event, value) => {
setFormData((prev) => ({ ...prev, city: value }));
};
const handleFileChange = (event) => {
setFormData((prev) => ({ ...prev, files: event.target.files }));
};
const onSubmitForm = async (data) => {
setLoading(true);
if (data.files) {
try {
const urls = await uploadFileToBlobStorage(data.files, setUploadProgress);
setFormData((prev) => ({ ...prev, urls }));
} catch (e) {
setError(e);
setLoading(false);
return;
}
import React, { useState, useEffect } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { TextField, Button, LinearProgress, Autocomplete, Card, CardContent, CardActions, List, ListItem, ListItemText } from '@material-ui/core';
import { useRecoilState } from 'recoil';
import { dataEntryFormState } from './dataEntryFormState';
import { uploadFileToBlobStorage, getBlobContainerFiles } from './azureStorage';
import { CosmosClient } from '@azure/cosmos';
import TagsField from './TagsField';
const cities = [
{ label: 'New York', value: 'NY' },
{ label: 'San Francisco', value: 'SF' },
{ label: 'Los Angeles', value: 'LA' },
{ label: 'Chicago', value: 'CHI' },
];
function DataEntryForm({ onSubmit }) {
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [error, setError] = useState(null);
const { control, handleSubmit, errors } = useForm({
defaultValues: {
name: '',
email: '',
city: null,
tags: [{ value: '' }],
files: null,
},
});
const [formData, setFormData] = useRecoilState(dataEntryFormState);
const { name, email, city, files } = formData;
const handleCityChange = (event, value) => {
setFormData((prev) => ({ ...prev, city: value }));
};
const handleFileChange = (event) => {
setFormData((prev) => ({ ...prev, files: event.target.files }));
};
const onSubmitForm = async (data) => {
setLoading(true);
if (data.files) {
try {
const urls = await uploadFileToBlobStorage(data.files, setUploadProgress);
setFormData((prev) => ({ ...prev, urls }));
} catch (e) {
setError(e);
setLoading(false);
return;
}
}
try {
const client = new CosmosClient({
endpoint: process.env.REACT_APP_COSMOSDB_ENDPOINT,
key: process.env.REACT_APP_COSMOSDB_KEY,
});
const database = client.database(process.env.REACT_APP_COSMOSDB_DATABASE);
const container = database.container(process.env.REACT_APP_COSMOSDB_CONTAINER);
const response = await container.items.create({
name: data.name,
email: data.email,
city: data.city?.label,
tags: data.tags.map((tag) => tag.value),
urls: formData.urls,
});
onSubmit(data);
} catch (error) {
console.error(error);
setError(error);
}
setLoading(false);
};
const [fileNames, setFileNames] = useState([]);
useEffect(() => {
const fetchFileNames = async () => {
const names = await getBlobContainerFiles();
setFileNames(names);
};
fetchFileNames();
}, []);
return (
<Card>
<CardContent>
<form onSubmit={handleSubmit(onSubmitForm)}>
<Controller
name="name"
control={control}
rules={{ required: true }}
as={<TextField label="Name" />}
error={!!errors.name}
helperText={errors.name ? 'Please enter a name' : ''}
/>
<Controller
name="email"
control={control