Using Form.Select from React Semantic UI with React-hooks - react-hooks

as the question suggests, I'm using RSUI with React-Hooks in a Next.js project and I'm trying to figure out how to send a payload from a Form.Select to a graphql endpoint. I've included a lot of extra code for context but really what I'm after is to successfully set "security_type" using setValues
import React, { useState } from 'react'
import Router from 'next/router'
import { Button, Checkbox, Form, Segment, Table } from 'semantic-ui-react'
import Layout from '../../components/layout'
import Loading from '../../components/loading'
import Error from '../../components/error'
import { useFetchUser } from '../../lib/user'
import { useQuery, useMutation } from '#apollo/react-hooks';
import query from '../../graphql/project/query';
import mutation from '../../graphql/project/mutation';
const security_types = [
{ key: 'Bank Guarantee', value: 'Bank Guarantee', text: 'Bank Guarantee', name: 'Bank Guarantee' },
{ key: 'Cash Retention', value: 'Cash Retention', text: 'Cash Retention', name: 'Cash Retention' },
{ key: 'Surety Bond', value: 'Surety Bond', text: 'Surety Bond', name: 'Surety Bond' },
];
function CreateProject() {
const { loading, error, data } = useQuery(query);
const [createProject] = useMutation(mutation,
{
onCompleted(data) {
Router.replace("/create_project", "/project/" + data.createProject.project_id, { shallow: true });
}
});
const { user, user_loading } = useFetchUser()
let [form, setValues] = useState({
project_number: '',
project_name: '',
security_type: '',
});
let updateField = e => {
console.log('e: ', e)
setValues({
...form,
[e.target.name]: e.target.value
});
};
let mutationData = ''
if (loading) return <Loading />;
if (error) return <Error />;
return (
<Layout user={user} user_loading={user_loading}>
<h1>Let's create a project</h1>
{user_loading ? <>Loading...</> :
<div>
<Segment>
<Form
onSubmit={e => {
e.preventDefault();
console.log('form: ', form)
createProject({ variables: { ...form } });
form = '';
}}>
<Form.Input
fluid
label='Project Number'
name="project_number"
value={form.project_number}
placeholder="Project Number"
onChange={updateField}
/>
<Form.Input
fluid
label='Project Name'
name="project_name"
value={form.project_name}
onChange={updateField}
/>
<Form.Select
fluid
selection
label='Security Type'
options={security_types}
placeholder='Security Type'
name="security_type"
value={form.security_type}
onChange={(e, { value }) => setValues(console.log('value: ', value), { "security_type": value })}
/>
<Button>Submit</Button>
</Form>
</Segment>
</div>
}
</Layout>
);
}
export default CreateProject;
I think all my troubles relate to the onChange section so any help would be great.

Related

How to test react component mocking fetch api?

I'm trying to test a react component where a fetch call occurs. The component:
class SearchResults extends React.Component<{ tag: string; setSpinner: (value: boolean) => void }> {
state: searchResultsState = {
results: [],
tag: '',
cardFull: null,
};
constructor(props: { tag: string; setSpinner: (value: boolean) => void }) {
super(props);
this.handleCardModal = this.handleCardModal.bind(this);
}
componentDidMount() {
getResponse(
this.props.tag,
(res) => {
this.setState({ results: res, tag: this.props.tag });
},
this.props.setSpinner
);
}
componentDidUpdate(prevProps: { tag: string }) {
if (this.props.tag !== prevProps.tag) {
getResponse(
this.props.tag,
(res) => this.setState({ results: res, tag: this.props.tag }),
this.props.setSpinner
);
}
}
handleCardModal() {
this.setState({ cardFull: null });
}
render() {
return (
<Fragment>
{this.state.cardFull && (
<CardFull data={this.state.cardFull} handleClick={this.handleCardModal} />
)}
{this.state.cardFull && <div className="blackout" onClick={this.handleCardModal} />}
<div className="search-results">
{this.state.results.length === 0 && this.state.tag !== '' && <div>Sorry, no matched</div>}
{this.state.results.map((result) => (
<CardUI
key={result.id}
className="card"
variant="outlined"
sx={{ minWidth: 275 }}
onClick={() => {
const currentCard = this.state.results.filter((res) => res.id === result.id)[0];
this.setState({ ...this.state, cardFull: currentCard });
}}
>
<CardMedia component="img" height="194" image={getUrl(result)} alt={result.title} />
<CardContent>
<p>{result.title}</p>
</CardContent>
</CardUI>
))}
</div>
</Fragment>
);
}
}
First I tried to use jest-fetch-mock.
import '#testing-library/jest-dom';
import { render } from '#testing-library/react';
import renderer from 'react-test-renderer';
import SearchResults from '../../src/components/SearchResults/SearchResults';
import sampleSearchResults from '../__fixtures__/sampleSearchResults';
import fetch from 'jest-fetch-mock';
fetch.enableMocks();
beforeEach(() => {
fetch.resetMocks();
});
const setSpinner = jest.fn();
describe('Search Results component', () => {
fetch.mockResponseOnce(JSON.stringify({ photos: sampleSearchResults }));
test('Search Results matches snapshot', () => {
const searchResults = renderer
.create(<SearchResults tag={''} setSpinner={setSpinner} />)
.toJSON();
expect(searchResults).toMatchSnapshot();
});
test('search results renders correctly', () => {
render(<SearchResults setSpinner={setSpinner} tag={'dove'} />);
});
});
But it gives the error during tests:
console.error
FetchError {
message: 'invalid json response body at reason: Unexpected end of JSON input',
type: 'invalid-json'
}
So, I've decided to mock fetch manually
import React from 'react';
import '#testing-library/jest-dom';
import { render, screen } from '#testing-library/react';
import renderer from 'react-test-renderer';
import SearchResults from '../../src/components/SearchResults/SearchResults';
import sampleSearchResults from '../__fixtures__/sampleSearchResults';
const setSpinner = jest.fn();
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ photos: sampleSearchResults }),
})
) as jest.Mock;
describe('Search Results component', () => {
test('Search Results matches snapshot', () => {
const searchResults = renderer
.create(<SearchResults tag={''} setSpinner={setSpinner} />)
.toJSON();
expect(searchResults).toMatchSnapshot();
});
test('search results renders correctly', () => {
render(<SearchResults setSpinner={setSpinner} tag={'dove'} />);
const title = screen.getByText(/Eurasian Collared Dove (Streptopelia decaocto)/i);
expect(title).toBeInTheDocument(); //mistake
});
});
Now fetch mock works correct, but it renders only one div - search results and doesn't render card. How can I test my component? Thank you.

How to make a graphql entry in a psql database

I am trying to figure out how to make a graphql entry in a psql database.
I am stuck and am not getting any feedback from console logs at any point in my attempt. I'm stuck for what to try next (or where to look for a tutorial showing how this step is supposed to work).
I have a table in my prisma schema called 'issue'. I am trying to create an 'issue' entry.
I have made a form with:
import * as React from "react"
import { Box, Center, Heading, Button, } from "#chakra-ui/react"
import { Select, OptionBase, GroupBase } from "chakra-react-select";
import { groupedIssueCategories } from "../components/issue/categories"
import { gql } from "#apollo/client"
import Head from 'next/head'
import { IssueInput, useAllIssuesQuery, useCreateIssueMutation } from "lib/graphql"
import * as c from "#chakra-ui/react"
import { Input } from "components/Input"
// import { Select } from "components/Select"
import { HomeLayout } from "components/HomeLayout"
import { Limiter } from "components/Limiter"
import { Form } from "components/Form"
import Yup from "lib/yup"
import { useForm } from "lib/hooks/useForm"
import { useMe } from "lib/hooks/useMe"
import { useToast } from "lib/hooks/useToast"
interface GroupedRiskOption extends OptionBase {
label: string
value: string
}
const _ = gql`
mutation CreateIssue($data: IssueInput!) {
createIssue(data: $data) {
id
title
issueCategory
description
userId
}
}
query AllIssues {
allIssues {
id
title
issueId
description
userId
}
}
`
export default function Issue() {
const toast = useToast()
const { me, loading: meLoading } = useMe()
const [createIssue] = useCreateIssueMutation()
const { data: issues, refetch } = useAllIssuesQuery()
const IssueSchema = Yup.object().shape({
title: Yup.string().required("Title is required"),
issueCategory: Yup.string().required("Category is required"),
description: Yup.string().required("Description is required"),
})
const form = useForm({ schema: IssueSchema })
const onSubmit = (data: IssueInput) => {
console.log(data)
return form.handler(() => createIssue({ variables: { data: { ...data, userId: me?.id || ""} } }), {
onSuccess: async () => {
toast({
title: "Issue created",
description: "Your issue has been created",
status: "success",
})
refetch()
form.reset()
},
})
}
if (meLoading)
return (
<c.Center>
<c.Spinner />
</c.Center>
)
if (!me) return null
return (
<Box>
<Head>
<title>Create Issue</title>
</Head>
<Limiter pt={20} minH="calc(100vh - 65px)">
<Center flexDir="column">
<Heading as="h1" size="3xl" fontWeight="extrabold" px="3rem" lineHeight="1.2" letterSpacing="tight" color="brand.orange">
Create Issue
</Heading>
<Form onSubmit={onSubmit} {...form}>
<c.Stack spacing={2}>
<c.Heading>Issues</c.Heading>
<Input autoFocus name="title" label="Title" placeholder="Eg: climate change" />
<Input name="description" label="Description" placeholder="Eg: Issues relating to climate change" />
<Select<GroupedRiskOption, true, GroupBase<GroupedRiskOption>>
// isMulti
name="issueCategory"
options={groupedIssueCategories}
placeholder="Select issue categories"
closeMenuOnSelect={false}
/>
<Button
color="brand.orange"
type="submit"
isFullWidth
isDisabled={form.formState.isSubmitting ||
!form.formState.isDirty}
isLoading={form.formState.isSubmitting}
>
Create Issue
</Button>
<c.List>
{/* {issues.allIssues.map((issue) => (
<c.ListItem key={issue.id}>
{issue.title}
{issue.issueCategory}
{issue.description}
</c.ListItem>
))} */}
</c.List>
</c.Stack>
</Form>
</Center>
</Limiter>
</Box>
)
}
Issue.getLayout = (page: React.ReactNode) => <HomeLayout>{page}</HomeLayout>
I have a create issue mutation in my lib/graphql:
export function useCreateIssueMutation(baseOptions?: Apollo.MutationHookOptions<CreateIssueMutation, CreateIssueMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useMutation<CreateIssueMutation, CreateIssueMutationVariables>(CreateIssueDocument, options);
}
export type CreateIssueMutationHookResult = ReturnType<typeof useCreateIssueMutation>;
export type CreateIssueMutationResult = Apollo.MutationResult<CreateIssueMutation>;
export type CreateIssueMutationOptions = Apollo.BaseMutationOptions<CreateIssueMutation, CreateIssueMutationVariables>;
When I click submit, nothing happens in the console. I can't log the data, and I can't see any errors, either in the terminal or in the console.
Can anyone give me a steer on where to look for insights as to what is going wrong. There is no data in the database, the onSuccess step doesn't get performed.

React form handleChange is not updating state

Form input onChange is not updating state. The action and reducer fire properly and backend rails API is updated, but the state does not change and nothing renders in the DOM.
I have used console logs to ensure that the action and reducer are working properly.
import React, { Component } from 'react';
import { Button, Form } from 'semantic-ui-react'
import { connect } from 'react-redux'
class TaskInput extends Component {
constructor() {
super()
this.state = {
name: ""
}
}
handleChange = (e) => {
this.setState({
name: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault()
this.props.addTask({name: this.state.name}, this.props.goal.id)
this.setState({
name: ''
})
}
render() {
return (
<Form className="new-task-form" onSubmit={(e) =>this.handleSubmit(e)}>
<Form.Field>
<label className="form-label">Add Task</label>
<input id="name" required value={this.state.name} onChange={(e) => this.handleChange(e)} />
</Form.Field>
<Button basic color='purple' type="submit">Add Task</Button>
<hr/>
</Form>
)
}
}
export default connect()(TaskInput)
import React, { Component } from 'react'
import { addTask, deleteTask } from '../actions/tasksActions'
import { connect } from 'react-redux'
import { fetchGoal } from '../actions/goalsActions'
import Tasks from '../components/Tasks/Tasks';
import TaskInput from '../components/Tasks/TaskInput';
class TasksContainer extends Component {
componentDidMount() {
this.props.fetchGoal(this.props.goal.id)
}
render(){
return(
<div>
<TaskInput
goal={this.props.goal}
addTask={this.props.addTask}
/>
<strong>Tasks:</strong>
<Tasks
key={this.props.goal.id}
tasks={this.props.goal.tasks}
deleteTask={this.props.deleteTask}
/>
</div>
)
}
}
const mapStateToProps = state => ({
tasks: state.tasksData
})
export default connect(mapStateToProps, { addTask, deleteTask, fetchGoal })(TasksContainer);
export default function taskReducer(state = {
loading: false,
tasksData: []
},action){
switch(action.type){
case 'FETCH_TASKS':
return {...state, tasksData: action.payload.tasks}
case 'LOADING_TASKS':
return {...state, loading: true}
case 'CREATE_TASK':
console.log('CREATE Task', action.payload )
return {...state, tasksData:[...state.tasksData, action.payload.task]}
case 'DELETE_TASK':
return {...state, loading: false, tasksData: state.tasksData.filter(task => task.id !== action.payload.id )}
default:
return state;
}
}
handleSubmit calls the action to addTask. handleChange updates state and renders the new task in DOM. handleSubmit is working. handleChange is not.

How to set null value for AutocompleteInput/ReferenceInput?

I AutocompleteInput wrapped ReferenceInput. In my case One Project has many Accounts. On edit account page I set project from available and save.
<ReferenceInput source="project_id" reference="projects" allowEmpty filterToQuery={searchText => ({ query_content: searchText })}>
<AutocompleteInput optionText="title" />
</ReferenceInput>
And now I need to set null for value project_id. It can even button which I could place near AutocompleteInput, but I don't know how set value straight to redux. Preferably I would like to avoid special http-request to API to reset this field.
Thanks!
i just took AutocompleteInput and append to it button to clear field. and call NullableAutocompleteInput. then also as earlier paste to ReferenceInput
<ReferenceInput source="field_id" reference="resources" allowEmpty filterToQuery={searchText => ({ query_title: searchText })}>
<NullableAutocompleteInput optionText={(choice) => optionRenderer(choice, 'Resource', 'title')} />
</ReferenceInput>
and whole code component
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import AutoComplete from 'material-ui/AutoComplete';
import BackspaceIcon from 'material-ui/svg-icons/content/backspace';
import IconButton from 'material-ui/IconButton';
import {FieldTitle} from 'admin-on-rest';
import {translate} from 'admin-on-rest';
export class NullableAutocompleteInput extends Component {
handleNewRequest = (chosenRequest, index) => {
if (index !== -1) {
const { choices, input, optionValue } = this.props;
input.onChange(choices[index][optionValue]);
}
}
getSuggestion(choice) {
const { optionText, translate, translateChoice } = this.props;
const choiceName = typeof optionText === 'function' ? optionText(choice) : choice[optionText];
return translateChoice ? translate(choiceName, { _: choiceName }) : choiceName;
}
clearData() {
this.props.input.onChange(null);
}
render() {
const {
choices,
elStyle,
filter,
input,
isRequired,
label,
meta: { touched, error },
options,
optionValue,
resource,
setFilter,
source,
} = this.props;
const selectedSource = choices.find(choice => choice[optionValue] === input.value);
const dataSource = choices.map(choice => ({
value: choice[optionValue],
text: this.getSuggestion(choice),
}));
return (
<div>
<AutoComplete
searchText={selectedSource && this.getSuggestion(selectedSource)}
dataSource={dataSource}
floatingLabelText={<FieldTitle label={label} source={source} resource={resource} isRequired={isRequired} />}
filter={filter}
onNewRequest={this.handleNewRequest}
onUpdateInput={setFilter}
openOnFocus
style={elStyle}
errorText={touched && error}
{...options}
/>
<IconButton onTouchTap={this.clearData.bind(this)} tooltip="Clear Data" tooltipPosition="top-right">
<BackspaceIcon color='grey' hoverColor='black'/>
</IconButton>
</div>
);
}
}
NullableAutocompleteInput.propTypes = {
addField: PropTypes.bool.isRequired,
choices: PropTypes.arrayOf(PropTypes.object),
elStyle: PropTypes.object,
filter: PropTypes.func.isRequired,
input: PropTypes.object,
isRequired: PropTypes.bool,
label: PropTypes.string,
meta: PropTypes.object,
options: PropTypes.object,
optionElement: PropTypes.element,
optionText: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
]).isRequired,
optionValue: PropTypes.string.isRequired,
resource: PropTypes.string,
setFilter: PropTypes.func,
source: PropTypes.string,
translate: PropTypes.func.isRequired,
translateChoice: PropTypes.bool.isRequired,
};
NullableAutocompleteInput.defaultProps = {
addField: true,
choices: [],
filter: AutoComplete.fuzzyFilter,
options: {},
optionText: 'name',
optionValue: 'id',
translateChoice: true,
};
export default translate(NullableAutocompleteInput);

Validation Error Message not getting displayed for custom validation in Angular 2

I have a register form where user need to provide username. When customer enters username, I want to show validation error message if that username already exists in db or not.
register.html
<-- code here-->
<div class="form-group">
<label for="username" class="col-sm-3 control-label">UserName</label>
<div class=" col-sm-6">
<input type="text" ngControl="userName" maxlength="45" class="form-control" [(ngModel)]="parent.userName" placeholder="UserName" #userName="ngForm" required data-is-unique/>
<validation-message control="userName"></validation-message>
</div>
</div>
<--code here-->
register.component.ts
import {Component} from 'angular2/core';
import {NgForm, FormBuilder, Validators, FORM_DIRECTIVES} from 'angular2/common';
import {ValidationService} from '../services/validation.service';
import {ValidationMessages} from './validation-messages.component';
#Component({
selector: 'register',
templateUrl: './views/register.html',
directives: [ROUTER_DIRECTIVES, ValidationMessages, FORM_DIRECTIVES],
providers: []
})
export class ParentSignUpComponent {
parentSignUpForm: any;
constructor(private _formBuilder: FormBuilder) {
this._stateService.isAuthenticatedEvent.subscribe(value => {
this.onAuthenticationEvent(value);
});
this.parent = new ParentSignUpModel();
this.parentSignUpForm = this._formBuilder.group({
'firstName': ['', Validators.compose([Validators.required, Validators.maxLength(45), ValidationService.nameValidator])],
'middleName': ['', Validators.compose([Validators.maxLength(45), ValidationService.nameValidator])],
'lastName': ['', Validators.compose([Validators.required, Validators.maxLength(45), ValidationService.nameValidator])],
'userName': ['', Validators.compose([Validators.required, ValidationService.checkUserName])]
});
}
}
validation-message.component
import {Component, Host} from 'angular2/core';
import {NgFormModel} from 'angular2/common';
import {ValidationService} from '../services/validation.service';
#Component({
selector: 'validation-message',
inputs: ['validationName: control'],
template: `<div *ngIf="errorMessage !== null" class="error-message"> {{errorMessage}}</div>`
})
export class ValidationMessages {
private validationName: string;
constructor (#Host() private _formDir: NgFormModel) {}
get errorMessage() {
let control = this._formDir.form.find(this.validationName);
for (let propertyName in control.errors) {
if (control.errors.hasOwnProperty(propertyName) && control.touched) {
return ValidationService.getValidatorErrorMessage(propertyName);
}
}
return null;
}
}
validation-service.ts
import {Injectable, Injector} from 'angular2/core';
import {Control} from 'angular2/common';
import {Observable} from 'rxjs/Observable';
import {Http, Response, HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/Rx';
interface ValidationResult {
[key:string]:boolean;
}
#Injectable()
export class ValidationService {
static getValidatorErrorMessage(code: string) {
let config = {
'required': 'This field is required!',
'maxLength': 'Field is too long!',
'invalidName': 'This field can contain only alphabets, space, dot, hyphen, and apostrophe.',
'userAlreadyInUse': 'UserName selected already in use! Please try another.'
};
return config[code];
}
static checkUserName(control: Control): Promise<ValidationResult> {
let injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
let alreadyExists: boolean;
if (control.value) {
return new Promise((resolve, reject) => {
setTimeout(() => {
http.get('/isUserNameUnique/' + control.value).map(response => response.json()).subscribe(result => {
if (result === false) {
resolve({'userAlreadyInUse': true});
} else {
resolve(null);
}
});
}, 1000);
});
}
}
}
Now, when i run, and give a username that already exists in db, the value of 'result' variable i am getting as false, which is expected and correct. But validation error message is not getting displayed. I am able to run and get validation error message for other custom validation functions. I am using Angular 2.0.0-beta.15. Can somebody help me to understand what could be the issue?
There are some known issues with async validation
https://github.com/angular/angular/issues/1068
https://github.com/angular/angular/issues/7538
https://github.com/angular/angular/issues/8118
https://github.com/angular/angular/issues/8923
https://github.com/angular/angular/issues/8022
This code can be simplified
return new Promise((resolve, reject) => {
setTimeout(() => {
http.get('/isUserNameUnique/' + control.value).map(response => response.json())
.subscribe(result => {
if (result === false) {
resolve({'userAlreadyInUse': true});
} else {
resolve(null);
}
});
}, 1000);
});
to
return http.get('/isUserNameUnique/' + control.value).map(response => response.json())
.timeout(200, new Error('Timeout has occurred.'));
.map(result => {
if (result === false) {
resolve({'userAlreadyInUse': true});
} else {
resolve(null);
}
}).toPromise();
Don't forget to import map, timeout, and toPromise.
If you use subscribe() instead of then() on the caller site, then you can event omit toPromise()
if you look into this -
'userName': ['', Validators.compose([Validators.required, ValidationService.checkUserName])] });
-- you can see I am using both synchronous and asynchronous validations together. When i changed method for checkUserName like 'Validators.composeAsync(ValidationService.checkUserName)' instead of Validators.compose method, error message got displayed.

Resources