Giter Club home page Giter Club logo

unform's Introduction

Unform

Easy peasy highly scalable ReactJS & React Native forms! 🚀

npm Coverage Status

Overview

Unform is a performance-focused API for creating powerful forms experiences for both React and React Native. Using hooks, you can build lightweight and composable forms based on ultra-extensible components. Integrate with any form library, validate your fields, and have your data out of the box.

Want to test Unform before using it?

ps: not available with React Native Web or Expo Web, use the iOS/Android devices in Expo Snack.

Need help?

We’re using GitHub Discussions to create conversations around Unform. It is a place for our community to connect with each other around ideas, questions, issues, and suggestions.

Roadmap

If Unform currently doesn't have a certain feature you think it's awesome, be sure to check out the roadmap to see if this is already planned for the future. Otherwise, we recommend you create a discussion describing your enhancement request.

Contributing

Thank you for being interested in making this package better. We encourage everyone to help improve this project with new features, bug fixes, or performance improvements. Please take a little bit of your time to read our guide to make this process faster and easier.

Contribution Guidelines

To understand how to submit an issue, commit and create pull requests, check our Contribution Guidelines.

Code of Conduct

We expect you to follow our Code of Conduct. You can read it to understand what kind of behavior will and will not be tolerated.

License

MIT © Rocketseat

unform's People

Contributors

brunolsantos avatar cesardenis avatar cleitonper avatar danilomartinelli avatar dependabot[bot] avatar diego3g avatar eliasgcf avatar harlancleiton avatar higoribeiro avatar italoiz avatar italomlp avatar jeffersonfilho avatar jpdemagalhaes avatar jpedroschmitz avatar kayotimoteo avatar lcnogueira avatar leonardobrito avatar lffg avatar luizbatanero avatar moiseshilario avatar morenomdz avatar pellizzetti avatar renovate-bot avatar rfbezerra avatar tavareshenrique avatar victorhas avatar victorsalesdev avatar vinifraga avatar vitorbertolucci avatar zaguiini avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unform's Issues

Customize Input on Validation Error

What would you like to be added:
Input customization when validation fail.

Why is this needed:
Cause this give us possibility of adding a custom style to the input when it is not valid.
For example: Change input border-color to RED

Preenchimento do Select, Textarea e Datapiker no Update

Doing my first test, i realize that the Select (simple e multiple) aren't marked with the value for initialData in the update moment. Like how the values of initialData are not passed on Textearea and Datapiker loading the form for update. Any sugestion for how to fix it?

Usage example/Demo

What would you like to be added:

It would be really nice if we could provide a demonstration of the package usage, with the code, preferentially at Code Sandbox. It would be a quick way to show what unform is all about and how it works.

It's really cool to show a few snippets on the README, but it would be more attractive to show them in real time, in a little project.

Why is this needed:

It would be more attractive to new users who might be interested in using unform to have a quick overview of it in action.

Is your enhancement request related to a problem? Please describe.

Not a problem, just one enhancement.

resetForm behaviour

What would you like to be added:
We have a resetForm method to be called after form submission. When this method is called, all fields will be cleared, even if default value supplied.
I think this behaviour is wrong if initialData supplied. I think the resetForm should set the initialData to fields.

Why is this needed:
Maybe, change this behaviour to reset fields to initialData and add another property to clear fields values.
clearForm and resetForm?

Regarding validation error message position

Description of issue

I'm not able to position the Yup validation error message

Usage example
This is an element:

<Input name="username" type="text" placeholder="Username" />

And I'm using this validation for the username field:

const schema = Yup.object().shape({
  username: Yup.string().required('Username is required')
})

The validation is called when the username field is empty and the message Username is required show up just after the <Input> field. After the validation message is called this is what I have:

<input type="text" placeholder="Username" id="username" name="username" aria-label="username" value="">
<span>Username is required</span>

Is it possible to position the validation message in another place?

Add async function support in initialData prop

What would you like to be added:

When I use other libraries like Formik, I have some trouble about async data, double loading (page loading using dynamic imports and data loading) is not a good approach for UX. Why not use a Promise resolve to get initialData?

Why is this needed:

I think about a simple function inside initialData prop like this:

async function fetchProfileInformation(){
    const res =  await fetch("/somelink");
    return res.data;
}

<Form initialData={fetchProfileInformation} >
    {...}
</Form>

Additional context

In typescript, a simple enhancement in prop verification is:

initialData: {} | () => Promise<{}>

Thank's for the attention.

Examples to React Hooks

Description of issue

There are no example to React Hooks.

Usage example

Add some examples to React Hooks.

Use custom type instead object for submit handler

What would you like to be added:

unform/lib/Form.tsx

make this changes

+ interface FormContent {
+    [key: string]: string;
+ }

interface Props {
  initialData?: object;
  children: React.ReactNode;
  context?: Context;
  schema?: ObjectSchema<object>;
-  onSubmit: (data: object, helpers: Helpers) => void;
+ onSubmit: (data: FormContent, helpers: Helpers) => void;
}

Is your enhancement request related to a problem? Please describe.

Typescript shows an error when we can try to access data parameter values with array syntax like this: data[key]. This occurs because data is typed with object type, and each value of object type has implicitly any type.

One way to solve this problem is to use a custom type, like above.

Additional context

unform-error
with object type
data[key] has implicit any type
unform-success
with FormContent type
data[key] has string type

Run lint-staged on tests and example files

What would you like to be added:

Run lint-staged in tests and example folder.

Why is this needed:

People have different editors and configuration and sometimes Prettier is messing with those files and Pull Requests get rejected because of style guide.

Is your enhancement request related to a problem? Please describe.

Not a problem itself, but there are a lot of PR's with linting problems.

Additional context

Maybe something like this solve the issue:

"lint-staged": {
  "lib/**/*.{ts,tsx}": [
    "eslint --fix",
    "prettier --write",
    "jest --bail --findRelatedTests"
  ],
  "__tests__/**/*.{ts,tsx}" : [
    "eslint --fix",
    "prettier --write"
  ],
  "example/**/*.{ts,tsx}" : [
    "eslint --fix",
    "prettier --write"
  ]
},

Loss of properties when using styled-component

Description of bug
When transforming component into a styled-component it loses properties as the type.

To Reproduce

Steps to reproduce the behavior:

  1. Create a styled-component with the input type unform
    ex:
import { Form, Input } from "@rocketseat/unform";
const InputText = styled(Input)`
  display: block;
`;
  1. import or component
  2. try changing the type to number
  3. See error

Expected behavior

list all properties

Discord channel

What would you like to be added:

Let's create a Discord channel for the project? We could have it on Rocketseat Discord server I believe.

Why is this needed:

Questions and Answers community channel.

TypeError: Cannot read property 'indexOf' of undefined

Fui aplicar em um projeto que utiliza reactstrap, mas toda vez que defino a linha:

import { Form, Input } from "@rocketseat/unform";

O console me lança esse erro:

TypeError: Cannot read property 'indexOf' of undefined

Alguém sabe como resolvo isso?

Lost Textarea component after issue #59

The componente Textarea was replaced to input with multiline attribute, but for this is not a good solution because this broken all applications was using Textarea component.
#59

In my opinion in this moment when de library is very new, its not a very big problem, but if I has multiple applications using unform and components has removed because other people resolve remove in new feacture, surely I would decide to stop using unform.

My suggestion is maintenance TextArea component and this component call the input with multiline param.

Concept bug, is not a functional bug at moment.

Scroll to first invalid element

What would you like to be added:
Scroll to first invalid form element when form is submitted

Why is this needed:
In large forms it is common the first fields are hidden when we submit the form, so that the user does not see the error.

Is your enhancement request related to a problem? Please describe.
No.

Additional context

Input multiline does not recive state

Not reported!

Description of bug
I was using componentWillReceiveProps(nextProps) to get the currently prop and using setState to add the prop to a state. So, I could to call the state and set the initialData with this state and show to user the text into the input. This was good! The text appeared in the Input, but not in the Input with multiline, so when I removed the multiline property, the text was shown.

To Reproduce
I think the bug is a error with multiline property, because when I remove the multiline, the text is shown.

Expected behavior

  1. Set componentWillReceiveProps(nextProps) reciving some data.
  2. Set a state into the componentWillReceiveProps(nextProps) passing the prop.
  3. Consume the data in the initialData.
  4. Nothing appears in the Input multiline.

Exception or Error
I hope the text is showing inside the input.


  state = {
    data: {},
  };

  componentWillReceiveProps(nextProps) {
    const data = nextProps.tool;
    this.setState({ data });
  }

render() {
    const { data } = this.state;
    const initialData = {
      description: data.description || '',
    };
    return (
       Form schema={schema} onSubmit={this.handleSubmit} initialData={initialData}
            Input multiline name="description"
       Form
    )
}

Environment:

  • Windows 10 Enterprise
  • Browser: Mozilla (67.0)
  • Node v11.11.0

Screenshots
carbon

[skip ci] tag being ignored

Describe the bug

It seems that [skip ci] is being ignored by Travis.

@diego3g @aldroydzito If you guys could take a look at it. <3

To Reproduce

Steps to reproduce the behavior:

  1. Create a pull request using the [skip ci] tag in the title;
  2. Watch as the build process still goes on.

Expected behavior

While using the [skip ci] tag in title of a pull request no build process should be triggered.

RegexPatterns embedded on input

What would you like to be added:

A new prop that will add some pre-set regex validtion to input.

Why is this needed:

Validate input is a major thing in forms. It would be nice to have some pre-set patterns for the developer to choose, without having to code it.

Additional context

Something like: <Input patternCep></Input>

patternCep looks like: [0-9]{5}-[\d]{3}

Use react-input-mask and unform

Description of issue
I'm trying use unform library, but i can't see a way to use react-input-mask too. Can i use unform with a className?

Usage example
<InputMask name="end_cep" mask="99999-999" maskChar="_" placeholder="Ex: 00000-000" className="ant-input" />

Clear value called infinitely times when useField with React Datepicker

Description of bug

When I integrate Unform with React DatePicker and use the resetForm after submitting values, the clearValue of registerField is called infinitely times. Maybe caused by the use of the hook useEffect like in the example present in the docs.

To Reproduce

I wrote code very similar to the examples. But, here is a sandbox:
https://codesandbox.io/embed/currying-moon-3fpyv

Expected behavior

Expected to clear form properly.

Exception or Error

Out of memory caused by infinitely calls to clearValue

Screenshots

issue

Environment:

Add information about your environment

  • OS: MacOS 10.14.4 Mojave
  • Browser: Google Chrome (74.0.3729.131)
  • Node 8.16.0
  • Npm 6.4.1
  • Yarn 1.15.2
  • Unform, react, react-dom, react-datepicker versions present in the sandbox provided

Additional context

When I said that this error maybe caused by the use of the useEffect hook, was because when I change it to the following, the code seems to run fine:

useEffect(() => {
    registerField({
      name: fieldName,
      ref: ref.current,
      path: "props.selected",
      clearValue: pickerRef => {
        console.log("ran clearValue");
        pickerRef.clear();
      }
    });
  }, [fieldName]); // eslint-disable-line

Erro na captura da função resetForm

Seguindo o tutorial para resetar o formulário após a submit, apresenta um erro. Segue abaixo o componente e em seguida o erro:

import React, {Fragment, Component} from 'react'
import {Redirect} from 'react-router-dom'

import * as Yup from 'yup'

import {Form, Input} from '@rocketseat/unform'
import UserList from '../../components/UserList'

import { isAuthenticated } from "../../services/auth";

import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import * as UserActions from '../../store/actions/users'


class Dashboard extends Component{
    schema = Yup.object().shape({
        name: Yup.string()
            .min(6, "Deve conter nome e sobrenome")
            .required("Nome é obrigatório"),
        email: Yup.string()
            .email("Deve ser um email válido")
            .required("Email é obrigatório"),
        password: Yup.string()
            .min(6, "Deve conter no mínimo 6 caracteres")
            .required("Password é obrigatório")
    })

    componentWillMount(){
        this.props.getUsersRequest()
    }

    handleSubmit = (user, {resetForm})=>{
        this.props.addUserRequest(user)
        // resetForm()
    }

    render(){
        if(!isAuthenticated()) return <Redirect to={"/"}/>
        return (
            <Fragment>
                <h1>Dashboard</h1>
                <Form schema={this.schema} onSubmit={this.handleSubmit}>
                    <label htmlFor="name">Nome:</label>
                    <Input id="name" name="name" placeholder="Nome do usuário" type="text"/>
                    <label htmlFor="email">Email:</label>
                    <Input id="email" name="email" placeholder="Nome do usuário" type="text"/>
                    <label htmlFor="password">Password:</label>
                    <Input id="password" name="password" placeholder="Nome do usuário" type="password"/>
                    <button type="submit">Enviar</button>
                </Form>
                <UserList/>
            </Fragment>
        )
    }
}

const mapStateToProps = state => ({
    users: state.users
})

const mapDispatchToProps = dispatch => bindActionCreators(UserActions, dispatch)

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)
ERRO: TypeError: r.inner is undefined

Use existing patterns to commits, versioning and changelog

Description of issue

Currently we are using our own commiting rules. Instead of it, would be interesting make use of a popular pattern like conventional commits. It's based on the the Angular convention and quite similar to the pattern we are using.

In addition, making use of this pattern we can enable cool features like automatic versioning and changelog management with the standart-version tool. This tool uses the Semantic Versioning pattern that's make the versions of this library more consistent with the made changes.

Usage example

feat(form): a new cool feature

BRAKING CHANGE: introducing a breaking change

Fix the issue #123

This commit will trigger a MAJOR update acording with Semantic Versioning rules.


Read more at Semantic Versioning.

Validating array fields

Hello,

I have been testing your lib for few hours and I really like it. On one of my projects we have a complex form builder which generates forms based on JSON. Lately we have some performance issue. Our bottle-neck is Formik, so I am looking for an alternative. I have recreated some code using unform, you can check it out here: https://codesandbox.io/embed/bold-hill-2ol405jn6r

I have encountered some problems with validating field arrays but I am not sure if it's yup or unform or just me. Honestly I don't have any experience with yup. Could you take a look on code?

Also I will need onBlur validation. I was thinking on passing onBlur function which will validate the field. Do you think it is possible to achieve? How about validation when one field value is dependent on another field? How it will impact on performance?

[RFC] Reset form data

There are many ways that we can provide for user to reset form data and clear all input fields, so the main discussion points here are:

  • Should we reset form after submit automatically?
  • How edit cases would work? Clear data or return to initial data?

My suggestion is to offer an helper inside onSubmit so user can reset data after submit like this:

function handleSubmit(data, { reset }) {
  // user function to deal with data
  reset();
}

Issue related: #16

Não da para usar esta biblioteca caso o projeto use o ant design

Description of bug
Hi Diego, i'm using ant design library in my project and i'm needing use your library too, but ant design library uses Input as a name like your project. How can i fix this conflict?

To Reproduce

Expected behavior

Exception or Error




Screenshots

Environment:

Additional context

got a warning when try select demo

when copy & paste select demo and run it on react 16.8.2 , got a warning:

Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().

code

import React, { useState } from "react";
import { Form, useField } from "@rocketseat/unform";
import Select from 'react-select';

/* You can't use your component directly, you have to wrap it
around another component, or you won't be able to use useField properly */
function ReactSelect({ name, options, multiple }) {
  const { fieldName, registerField, defaultValue, error } = useField(name);
  const [value, setValue] = useState(defaultValue);

  function getValue() {
    if (!multiple) {
      return value;
    }

    return value.reduce((res, item) => {
      res.push(item.value);
      return res;
    }, []);
  }

  return (
    <>
      <Select
        name="techs"
        options={options}
        isMulti={multiple}
        value={value}
        onChange={setValue}
        ref={() => registerField({ name: fieldName, ref: getValue })}
      />

      {error && <span>{error}</span>}
    </>
  )
}

export default function App() {
  const techs = [
    { value: "react", label: "ReactJS" },
    { value: "node", label: "NodeJS" },
    { value: "rn", label: "React Native" }
  ];

  const colors = [
    { value: "red", label: "Red" },
    { value: "green", label: "Green" },
    { value: "blue", label: "Blue" }
  ]

  const initialData = {
    color: { value: 'green', label: 'Green' },
    techs: [
      {
        value: 'react', label: 'ReactJS'
      },
    ],
  }

  function handleSubmit(data) {};

  return (
    <Form initialData={initialData} onSubmit={handleSubmit}>
      <ReactSelect options={colors} name="color" />

      <br />

      <ReactSelect options={techs} name="techs" multiple />

      <button type="submit">Save</button>
    </Form>
  );
}

focus cycle

I would like to propose two new features, one indicating which should be the first field to receive the focus and the other indicating the next field where the focus should jump when the user press enter or tab. Thus, in the resetform the focus could return to the first field and cycle again

[RFC] React Native Support

What would you like to be added:

React Native support 🎉

Why is this needed:

Currently, Unform only works with web projects using ReactJS but a port to React Native could be created.

Is your enhancement request related to a problem? Please describe.

No.

Additional context

Unform can easily be integrated to React Native TextInput's as these components references also store their value as a prop called _lastNativeText (even in uncontrolled components):

Screen Shot 2019-05-17 at 14 34 33

My worry about this is that React Native has different input types from user, pickers like DatePicker, FilePicker, DocumentPicker probably won't have an API to work with reference.

I think we should discuss more about how to integrate these elements or limit unform responsibilities inside React Native.

Add new prop "multiline" to input and remove Textarea

What would you like to be added:

Add a prop to Input:

<Input multiline />

And now it will act as a textarea.

Why is this needed:

Input and textarea are common elements, they both act the same way and we have redundant code between the two components.

Is your enhancement request related to a problem? Please describe.

No.

Additional context

React Native already do this way, so why not :)

Function components cannot be given refs

When I try to reference a function component it returns: Function components can not be given refs. Attempts to access this ref will fail.

The component used was:

import { MuiPickersUtilsProvider, KeyboardDatePicker } from '@material-ui/pickers';

const DatePickers = ({ name, ...rest }) => {
  const ref = useRef();
  const { fieldName, registerField, defaultValue, error } = useField(name);
  const [selected, setSelected] = useState(defaultValue);

  useEffect(() => {
    registerField({
      name: fieldName,
      ref: ref.current,
      path: 'props.selected',
      clearValue: pickerRef => {
        pickerRef.clear();
      },
    });
  }, [ref.current, fieldName]);

  return (
    <KeyboardDatePicker 
      ref={ref} 
      name={fieldName}
    />
  );
};

Set errors from outside

What would you like to be added:

Add setErrors function in the helper. it helps to set errors on submit.

Why is this needed:

Some time API returns validation errors after submitting data and we need to add each field related errors. (like unique validation)

[RFC] Checkbox implementation

Im thinking on the implementation of the checkbox functionality, and ended in this idea:

  • work with an array of options, like select field
  • options array will contain id and label (each option)
  • getValue will return an array of checked ids

Well, let me know what you think about

Set the resetForm call as an element attribute

What would you like to be added:
Set if the form is reset after submitting with a tag attribute as in this example:

        <Form onSubmit={this.handleUpdate} resetForm>
          <FormInput type="hidden" name="id" value={item.id} />
          <FormInput type="text" name="text" placeholder={item.text} />
          <FormInput type="text" name="type" placeholder={item.type} />
          <FormInput type="text" name="value" placeholder={item.value} />
          <FormInput type="text" name="duration" placeholder={item.duration} />
          <button type="submit" className="teal-btn">
            Update
          </button>
        </Form>

This could be done by checking if the resetForm prop is present, it can also be used to handle issue #67 if that change is implemented by passing the props data to specify what time of reset is done.

Why is this needed:
It may be better semantic wise and you may need to reset one form but not another while using the same submit method in both.

Is your enhancement request related to a problem? Please describe.
No.

Who's using Unform (add your project)

We have nice projects using Unform already, it would be very cool to include a section inside this project with project links.

What do you think about?

Cannot read property 'indexOf' of undefined

Description of bug
I just put a Input and have an error

<UnformInput className="ant-input" style={{ width: '90%' }} />
To Reproduce

Expected behavior
Cannot read property 'indexOf' of undefined

Exception or Error




Screenshots
2019-05-20

Environment:

Additional context

Version 1.3.0 removing props

In version 1.3.0, it is removing the form's properties, like the Id, and returning only a data-testid, losing all the stylization done.

Pass a React component as prop to an input.

What would you like to be added:
Option to pass a React component as a prop

Why is this needed:
If I'm using a UI lib such as Material-UI, I could pass my custom component.

Is your enhancement request related to a problem? Please describe.
I guess no, maybe #49

I can get this one if you guys like the idea 😄

Form main functionalities like get data may be exported too

What would you like to be added:
Some functionalities may be exported from the form itself, like getting data outside the onSubmit, reset form outside onSubmit too, and so on.

Why is this needed:
I think that it is a good feature to introduce. Some developers want to control the form by its hand. So with this functionalities, they can control the form without the need to be in the on submit function.

E.g.: get data of the form without submitting, or clear data manually.

Is your enhancement request related to a problem? Please describe.
No.

Additional context

I was working on #73, and face this. I already have the code in mind (and already made a working getData function). What do you guys think about this?

[RFC] Input type file support

I noticed that the Input component does not register the values for type="file". I think it would be interesting to add this feature to the library.

With that in mind, I thought of two ways to do this:

  • Change the Input component to handle the onChange property.
  • Create a new FileInput component just for this purpose.

Using any of the ways suggested above, we would have an answer like:

{
  "attach": "data:text/csv;base64..."
}

Examples

Creating a new FileInput component would normally be like the other components:

<Form>
  <FileInput name="attach" />
</Form>

Using the Input component:

<Form>
  <Input name="attach" type="file" />
</Form>

Select does not change initialState when rendering again.

Description of bug

Select does not change initialState when rendering again.

To Reproduce

  1. I will make the first render, set the initialState.
  2. When rendering, input and selects are set to initialState.
  3. Changing the first select changes the react states.
  4. When changing states react will again render input changes to new states but selects do not change.

Screenshots

  telaChange = (selectedOption:any) => {
      const { telas } = this.props;
      const tela = telas[selectedOption.target.value - 1];
      const { nometela, subtelaqtd, turnoqtd } = tela;
      this.setState({
              telaselect: parseInt(selectedOption.target.value),
              nometela,
              subtelaqtd,
              turnoqtd,
      });
    };


render() {
    const {
      telaselect,
      nometela,
      subtelaqtd,
      turnoqtd,
    } = this.state;

    const formData = {
      telaselect,
      nometela,
      subtelaqtd,
      turnoqtd,
    };

      return (
          {console.log(formData)}
          <Form initialData={formData} schema={schema} onSubmit={this.handleSubmit}>
              <Select 
					  className="input",
					  name="telaselect" ,
					  options={this.telasOptions()} ,
					  onChange={this.telaChange} />
              <Input className="input" name="nometela" type="name" placeholder="Nome" />
              <Select className="input" name="subtelaqtd" options={subtelasOptions} />
              <Select className="input" name="turnoqtd" options={turnoOptions} />
              <button className="form-btn" type="submit">Editar tela</button>
          </Form>
		)

bug unform

Environment:

  • OS: Ubuntu
  • Browser Chrome (75.0.3770.142),
  • Node [10.16.0]
  • create-react-app --typescript

Auto Save on blur

Auto Save on blur, select or check

An option to set Form with prop autoSave and when this props was seted the form will save automatically when the user blur the input or select an option

Field <Select /> does not send initialData if it does not change the value

I'm using the initialData for a <Select /> field and it already appears with the selected value. When I change the select, the form is sent with the correct values, but if I leave default, the value of the field gets undefined

const selectExample = [
  {
    id: "id1",
    title: "Teste"
  },
  {
    id: "id2",
    title: "Teste2"
  }
];

const initialExample = {
  select: "id2"
};

return (
  <Form initialData={initialExample} onSubmit={this.handleSubmit}>
    <Select name="select" options={selectExample} />
    <br />
    <br />
    <button type="submit">Enviar</button>
  </Form>
);

Captura de Tela 2019-05-13 às 19 36 09

Captura de Tela 2019-05-13 às 19 36 22

Add commit linting

Today, even with contribution guide, commits can have more than 50 characters in title and 72 columns in description.

We can add Commitlint with Husky to lint the commit message before commit reaches our Github.

We can also add it to Travis to double check any bypasses from developer.

[RFC] New Unform API

Main problem

Unform was released some months ago and we're receiving a lot of feature suggestions that can't be implemented with the current Unform API.

Example: If we want to set an input value programatically it's not possible. If we want to get/set an error message programatically it's not possible. If we want to use any form data outside the onSubmit function, it's not possible.

Due to this, i was studying ways to keep unform simple and fast but give developer access to simple functions like getting/setting an input value, getting/settings error messages, etc.

Proposed API

After many tests i got something like this that i want to share with you guys:

import React from 'react';
import axios from 'axios';
import * as Yup from 'yup';
import { useForm, Form, Input } from '@rocketseat/unform';

export default function App() {
  const [{ setValue }, formRef] = useForm({
    initialData: { name: 'Diego' },
    schema: Yup.object().shape({
      name: Yup.string().required(),
    })
  });

  async function handleCepChange(e) {
    const cep = e.target.value;

    const response = await axios.get(`https://viacep.com.br/ws/${cep}/json`);

    setValue('street', response.data.logradouro);
  }

  async handleSubmit(data) {

  }

  return (
    <Form onSubmit={handleSubmit} ref={formRef}>
      <Input name="cep" onChange={handleCepChange} />
      <Input name="street" />
    </Form>
  );
}

Main points here:

  • We are using ref in our form to access all it properties and methods;
  • We do not listen to input changes from our form but from input directly so we still keep not controlling inputs;
  • We are moving initialData, schema and other form properties (should we?), maybe we could keep this inside <Form /> tag.

RFC

We need suggestions and discussions about this new proposed API so every comment here is welcome ❤️

Clear inputs after submit

I have the following code:

import React, { useState } from 'react';

import Calendar from 'react-calendar';
import { Form, Input } from '@rocketseat/unform';
import * as Yup from 'yup';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import { Creators as PostsActions } from '~/store/ducks/posts';

function Main({ savePostRequest, getPostsRequest, posts }) {
  const today = new Date();

  function handleSubmit(data) {
    const { post } = data;
    savePostRequest({ post, date });
  }

  return (
    <Container>
         <Form schema={schema} onSubmit={handleSubmit}>
                <Input
                    type="text"
                    name="post"
                    placeholder={
                    'Type something you are grateful for and press "Enter" to share with everyone'
                    }
                    autoComplete="off"
                    disabled={posts.isSending}
                    autoFocus
                />
            </Form>   
    </Container>
  );
}

const mapStateToProps = state => ({
  posts: state.posts,
});

const mapDispatchToProps = dispatch => bindActionCreators(PostsActions, dispatch);

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(Main);

How to I clear the input field after form submit?

Infinite render on DatePicker example, when using eslint and prettier.

Description of issue

When I copy and paste the example of the documentation of DatePicker it render infinitely times, this bug do the browser use a lot of memory and after some time crash.

That bug happened because of my eslint + prettier config, both changed my useEffect dependencies to [fieldName, registerField] but the right one are [ref.current, fieldName].

I solved the issue adding a eslint-disable-next-line on my code.

Like this:

useEffect(() => {
    registerField({
      name: fieldName,
      ref: ref.current,
      path: 'props.selected',
      clearValue: pickerRef => {
        pickerRef.clear()
      },
    })
    // eslint-disable-next-line
  }, [ref.current, fieldName])

It would be good add a warning on the documentation to the new users of the lib to take care of that, because it is a little tricky.

I mean something like:
Observation: If you are using eslint + prettier you need to look for your useEffect dependencies, they will change when you format your code and that will cause a bug of infinite render. You can fix it adding a eslint-disable-next-line comment on the line above of the useEffect dependencies.

OBS: I don't also if the right place to put this is on the documentation, is there a wiki or a common issues page?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.