I have such a component in which I set initial state from props:
class CarsModal extends PureComponent {
constructor(props) {
super(props);
autoBind(this);
const { data } = {} } = props;
this.state = {
selectedCar: data.category || '',
cars: [],
isSpam: data.spam,
pick: data.pick,
suitable: data.suitable,
articles: false,
show: false,
};
this.messageTimer = 0;
}
async componentDidMount() {
const cars = await getCars();
this.setState({
cars,
});
}
componentWillUnmount() {
clearTimeout(this.messageTimer);
}
close() {
}
select(car) {
this.setState({
selectedCar: car,
});
}
async save(scrapeRequest = false) {
const { carId } = this.props;
const {
selectedCar,
isSpam,
pick,
suitable,
articles,
} = this.state;
await curateCar(storyId, {
selectedCar,
is_spam: isSpam,
pick: pick,
suitable: suitable,
articles: articles,
scrape: scrape,
});
if (!scrape) {
this.setState({
show: true,
});
clearTimeout(this.messageTimer);
this.messageTimer = setTimeout(() => {
this.setState({
show: false,
});
}, 1500);
}
}
scrape() {
this.save(true);
}
toggle(key) {
this.setState((state) => ({
[key]: !state[key],
}));
}
render() {
const { show, curatorData } = this.props;
const { author, cars, show } = this.state;
return (
<Modal
show={show}
onHide={this.handleClose}
dialogClassName={cx('curate-modal')}
centered
>
<ionClick={this.close} />
<h3>Tools</h3>
<div>
<span>Auto:</span>
<DropdownButton
title={(
<>
{selectedAuthor}
<i />
</>
)}
>
{cars.map((car) => (
<Dropdown.Item
key={author}
active={author === car}
onClick={() => this.select(author)}
>
{author}
</Dropdown.Item>
))}
</DropdownButton>
</div>
{OPTIONS.map((option) => (
<Option
key={option.key}
id={option.key}
checked={this.state[option.key]}
onChange={() => this.toggle(option.key)}
>
{option.content}
</Option>
))}
<div className={cx('update-info')}>
<button
type="button"
onClick={() => this.save()}
>
Update
</button>
{showMessage && (
<span>Updated</span>
)}
</div>
<hr />
<span
className={cx('link')}
onClick={this.scrape}
>
Scrape article
</span>
<a href='/'>Test 1</a>
<a href='/'>Vtest 2</a>
</Modal>
);
}
}
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators({ ...actions }, dispatch),
});
const mapStateToProps = (state) => ({
userData: state.reducer.userData,
});
but I know that setting initial state from props is antipattern. I tried to use getDerivedStateFromProps(nextProps, prevState)
React component initialize state from props
But after that my state updates everytime and didn't change actually, is it updates with same props everytime. I need to set initial state only on INITIAL
load. How can I do that?