0

Hi I want to do setState and then run function. I receive this error: Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect(). console.

my code:

import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { addPostOptions } from '../../actions/post';

const NewPostOptions = ({ addPostOptions, category: { selected } }) => {
    const [optionData, setOptionData] = useState({
        transaction_type: ''
    });



    const {
        transaction_type
    } = optionData;


    const onChange = e => {
        setOptionData({ ...optionData, [e.target.name]: e.target.value }, () => addPostOptions(optionData));
    }

    return selected.id === 1001 ? (
        <div class="form-group">
            <p>Hello</p>
        </div>
    ) :
        selected.id === 102 ? (
            <div class="form-group">
                <input
                    type="text"
                    placeholder="Title"
                    name="transaction_type"
                    value={transaction_type}
                    onChange={e => onChange(e)}
                />
                <small class="form-text">You should set a title</small>
            </div>
        ) :
            (
                <div></div>
            )
}

NewPostOptions.propTypes = {
    addPostOptions: PropTypes.func.isRequired
}

const mapStateToProps = state => ({
    category: state.category,
});

export default connect(mapStateToProps, { addPostOptions })(NewPostOptions)```

MaK
  • 121
  • 1
  • 8

1 Answers1

0

As the error says. remove the second argument in setOptionDate function. and use the useEffect. the effect will run after every change to the optionData state.

useEffect(() => {
   addPostsOptions(optionData);
}, [optionData, addPostsOptions]);
rotemls98
  • 187
  • 1
  • thanks it work, can you help me on same problem with onSubmit https://stackoverflow.com/questions/59429540/onsubmit-function-setstate-doesnt-work-the-first-time – MaK Dec 20 '19 at 20:09