Redux toolkit returns the previous state when you make a request for data, how do I fix this?

crispenn 注册会员
2023-01-25 21:38

if you need to add side effects like interacting with a database to synonymously update both frontend and backend, try using redux saga or redux thunks.These help you handle asynchronous operations easily. https://redux-saga.js.org/

2023-01-25 21:38

This is not a Redux issue. The behavior you're seeing is because the savedBookmark function is a "closure" that captured the value of the selected data at the time that the React component rendered. When you dispatch(), the Redux store itself is immediately updated, but A) this component hasn't had a chance to re-render yet, and B) even when it re-renders this function instance will always point to the old data that existed at the time the function was created.

This is also true for any React component state update as well:

const [counter, setCounter] = useState(0);

const handleIncrementClick = () => {
  setCounter(counter + 1);
  console.log(counter); // still the old value!

This is a very common point of confusion.

If you need to get the newly updated Redux store state immediately after a dispatch, then yes, the right answer here is to do that in a thunk where you have access to getState():


About the Author

Question Info

Publish Time
2023-01-25 21:38
Update Time
2023-01-25 21:38

Related Question




Visual Studio for Mac 2022预览更改快捷键

Spark withcolumnrename不会在for循环中工作



IsUpdateable返回false salesforce

python绘图报错:TypeError: unsupported operand type(s) for -: 'method' and 'float'

Salesforce LWC编辑器chrome扩展错误