Вы можете решить это так:
- имеет
Loader
компонент, который загружает данные, если получает URL
- передать URL этому компоненту, если
touched[fieldName] && !errors[fieldName]
Loader
компонент может быть как
import { PureComponent } from 'react';
import PropTypes from 'prop-types';
import superagent from 'superagent'; // swap to your xhr library of choice
class Loader extends PureComponent {
static propTypes = {
url: PropTypes.string,
onLoad: PropTypes.func,
onError: PropTypes.func
}
static defaultProps = {
url: '',
onLoad: _ => {},
onError: err => console.log(err)
}
state = {
loading: false,
data: null
}
componentDidMount() {
this._isMounted = true;
if (this.props.url) {
this.getData()
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.url !== this.props.url) {
this.getData(nextProps)
}
}
componentWillUnmount() {
this._isMounted = false
}
getData = (props = this.props) => {
const { url, onLoad, onError } = props;
if (!url) {
return
}
this.setState({ data: null, loading: true });
const request = this.currentRequest = superagent.
get(url).
then(({ body: data }) => {
if (this._isMounted && request === this.currentRequest) {
this.setState({ data, loading: false }, _ => onLoad({ data }));
}
}).
catch(err => {
if (this._isMounted && request === this.currentRequest) {
this.setState({ loading: false });
}
onError(err);
});
}
render() {
const { children } = this.props;
return children instanceof Function ?
children(this.state) :
children || null;
}
}
Если URL не передан, он ничего не делает. При изменении URL-адреса загружаются данные.
Использование в Formik
render / children prop:
<Loader
{...(touched[fieldName] && !errors[fieldName] && { url: URL_TO_FETCH })}
onLoad={data => ...save data somewhere, etc.}
/>