0
Follow
0
View

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/

DIANMANYU 注册会员
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():

https://redux.js.org/usage/writing-logic-thunks#accessing-state

About the Author

Question Info

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

Related Question

最后一个,关于this指针的

c语言数组和for循环

指针下for循环中的scanf

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

Spark withcolumnrename不会在for循环中工作

关于逗号表达式在for语句中的应用

Cypress:使用大json文件的forEach循环在启动前崩溃测试

IsUpdateable返回false salesforce

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

Salesforce LWC编辑器chrome扩展错误