I\'m learning react and it\'s great, but i\'ve ran into an issue and i\'m not sure what the best practice is to solve it.
I\'m fetching data from an API in my compon
I set initial state in constructor. You can of course set initial state of component as static value - empty array or object. I think better way is to set it using props. Therefore you can use you component like so
or
(which takes value of items from defaultProps
object because you not pass it as prop).
Example:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [], // or items: {...props.items}
};
}
async componentDidMount() {
const res = await this.props.getItems();
this.setState({items: res.data.items})
}
render() {
return
}
};
App.defaultProps = {
items: []
}