reactjsrecompose

How do I clean up form using recompose in reactjs?


After form submit I want to clean it but this solution doesn't seem to work. here's my submit handler:

handleSubmit: ({ title, body }, props) => e => {
    e.preventDefault()
    props
        .handleCreatePost({
            variables: {
                title,
                body
            }
        })
        .then(() => {
            return {
                title: "",
                body: ""
            }
        })
        .catch(err => console.log(err))
}

Solution

  • Every time you need to change props from inside of your component you have to use withStateHandlers.

    compose(
      withStateHandlers(
        ({title, body})=> ({title, body}), //set the state from parent props
        { 
          setTitle: () => title => ({title}), // update the title
          setBody: () => body => ({body}), // update the body
          clearProps: () => () => ({titel:'', body: ''}) // create a handler to reset the values
        }
      ),
      withHandlers({
        handleSubmit: ({ title, body, clearProps }, props) => e => {
          e.preventDefault()
          props
            .handleCreatePost({
              variables: {
                title,
                body
              }
            })
            .then(clearProps) // reset the values 
            .catch(err => console.log(err))
          }
        )
    )