Er.Se
Er.Se

Reputation: 476

React useState gets previous value after history.push

I am trying to change URL when <RadioGroup onChange={handleCategoryChange}/> event fired:

const history = useHistory();
const { categoryId } = props;
const [category, setCategory] = useState(categoryId);

const handleCategoryChange = event => {
    history.push(`/books/${event.target.value}`)
};

Url will change according to categoryId parameter.

But when the page re-renders with new categoryId it still gets the previous value while I am expecting it to set the new categoryId

const [category, setCategory] = useState(categoryId);

Upvotes: 2

Views: 495

Answers (1)

Or Assayag
Or Assayag

Reputation: 6336

You should update the new value:

const history = useHistory();
const { categoryId } = props;
const [category, setCategory] = useState(categoryId);

const handleCategoryChange = event => {
    setCategory(event.target.value);
    history.push(`/books/${event.target.value}`)
};

Upvotes: 1

Related Questions