rofrischmann/alveron

View on GitHub
website/docs/examples/contact-form.mdx

Summary

Maintainability
Test Coverage
# Contact Form

> The source code for all examples can be found on [Github](https://github.com/robinweser/alveron/tree/master/website/examples/).

This example is closer to real-world usage and shows how effects can be used to incorporate asynchronous behaviour such as data fetching and API calls.

## Coverage

- Model
- Actions
- Actions with Payload
- Effects

<Box
  padding={8}
  marginTop={8}
  marginBottom={-3}
  extend={{ border: '1px solid rgb(220, 220, 220)' }}>
  <ContactForm />
</Box>

```js
function sendForm(data, onSuccess, onError) {
  setTimeout(() => {
    if (data.firstName && data.lastName && data.email) {
      alert('Success!')
      onSuccess()
    } else {
      onError('Data missing!')
    }
  }, 2000)
}

const model = {
  loading: false,
  error: null,
  firstName: '',
  lastName: '',
  email: '',
}

const actions = {
  setFirstName: (state, firstName) => [
    {
      ...state,
      firstName,
    },
  ],
  setLastName: (state, lastName) => [
    {
      ...state,
      lastName,
    },
  ],
  setEmail: (state, email) => [
    {
      ...state,
      email,
    },
  ],
  submitForm: (state, data) => [
    {
      ...state,
      loading: true,
    },
    (actions) => sendForm(data, actions.onSuccess, actions.onError),
  ],
  onError: (state, error) => [
    {
      ...state,
      loading: false,
      error,
    },
  ],
  onSuccess: (state) => [model],
}
```