All files / Form index.js

100% Statements 27/27
100% Branches 10/10
100% Functions 10/10
100% Lines 23/23
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60      4x 1x 1x 1x   2x 4x 4x 4x 4x 4x 4x         12x 12x 4x         8x         3x 3x     1x             1x 1x         12x 12x 12x                  
import React from "react"
import _ from "lodash"
 
export const joinPaths = (...paths) => paths.filter(Boolean).join(".")
export const Context = React.createContext({})
export const useForm = () => React.useContext(Context)
export const PathContext = React.createContext("")
 
export const withField = BaseComponent => props => {
    const { data, set } = React.useContext(Context)
    const path = React.useContext(PathContext)
    const finalPath = joinPaths(path, props.path)
    const value = finalPath ? _.get(data, finalPath) : data
    const setValue = React.useCallback(val => set(finalPath, val), [finalPath])
    return <BaseComponent setValue={setValue} value={value} {...props} />
}
 
export default class extends React.Component {
    static getDerivedStateFromProps(props, state) {
        const { initialData } = props
        if (initialData !== state.initialData) {
            return {
                data: initialData,
                initialData
            }
        }
        return null
    }
    state = {
        data: this.props.initialData || {},
        set: (path, value) => {
            let data = JSON.parse(JSON.stringify(this.state.data))
            this.setState(_.set({ data }, `data.${path}`, value))
        },
        reset: () => {
            this.setState({
                data: this.props.initialData || {}
            })
        }
    }
 
    handleSubmit = e => {
        e.preventDefault()
        this.props.onSubmit(this.state.data, this.state)
    }
 
    render() {
        // eslint-disable-next-line no-unused-vars
        const { children, initialData, ...props } = this.props
        const { Provider, Consumer } = Context
        return (
            <Provider value={this.state}>
                <form {...props} onSubmit={this.handleSubmit}>
                    {typeof children === "function" ? <Consumer>{children}</Consumer> : children}
                </form>
            </Provider>
        )
    }
}