S
S
Shiva62019-11-10 21:38:43
JavaScript
Shiva6, 2019-11-10 21:38:43

How to immediately return a new state from useState after a change?

Hello everyone reading this question!
There is a selector whose value works as a filter:

const { Option } = Select;
  const dispatch = useDispatch();
  const [filters, setFilters] = useState({status: null});

  <Select
      style={{ width: 100 }}
      placeholder="Статус"
      optionFilterProp="children"
      onChange={onChangeStatus}>
    <Option value="created">Создан</Option>
    <Option value="added">Добавлен</Option>
    <Option value="photo">Фотография продукта</Option>
  </Select>

When one of the values ​​inside the selector is selected, a state-changing event fires;
function onChangeStatus(value) {
    setFilters({ status: value})
    dispatch(getFilters(filters));
  }

But the fact is that the old state {status: null} comes to the action, I just can’t write the asynchrony correctly so that the state has time to change and only then dispatch works. I rewrote the function in this form, but there is an error in the console.
function onChangeStatus (value) {
    setFilters({
      ...filters, status: value
    }, () => {
      dispatch(getFilters(filters));
    });
  }

Thanks in advance for any help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Guccigang, 2019-11-10
@Shiva6

And why not pass { status: value } to `getFilters` immediately, to which we have access in the function?

M
Miniwe, 2019-11-23
@jumbastic

...
onChange={value => setFilters({status: value})}>
...
useEffect(() => {
dispatch(getFilters(filters));
}, [filters])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question