Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

reactjs - Share states between two reducers (React +Redux)

I have these two reducers

const getPosts = (initialState = {posts: []}, action) => {...}

const createPost = (initialState = {post: null}, action) => {...}

where getPosts reducer puts the fetched posts performed by the associated action creator in the state variable posts, while createPost puts the created post in the state variable post. The action creator associated with the createPost stores the post into the database in the backend, and after storing the post in the database, I would like to update the posts on the page in the frontend from getPosts without fetching all the posts again from the database again because I already have all the posts in the state but the new one. So, what I am trying to do is to push the created post into the posts state variable, but both states are in different reducers. How can I push the post state variable's value into the posts state variable to achieve an update at the frontend without fetching all the posts again after each post creation?

question from:https://stackoverflow.com/questions/65923632/share-states-between-two-reducers-react-redux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you dispatch the action that creates the new post, you can also dispatch an action that adds it to the getPosts reducer.

Alternatively, when the POST succeeds from creating the new post in the db, you can then dispatch the action that adds it to the getPosts` reducer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...