Getting a ID back from a reducer in redux Getting a ID back from a reducer in redux reactjs reactjs

Getting a ID back from a reducer in redux


I think that you should dispatch only one action here: addBookmark(), which accepts both bookmark object and folder.

Your code, which handles adding bookmark object into folder should be part of reducer.

Also, refer the Todos example in Redux project. It has id provided in action creation to make it possible to read it in the component. You can also use current state to compute latest id:

function addBookmark(bookmark, folder) {   return (dispatch, getState) => {       const newBookmark = Object.assign({         id: Math.max(0, ...getState().bookmarks.map(b => b.id)) + 1,       }, bookmark);       dispatch({         type: 'ADD_BOOKMARK',         bookmark: newBookmark,         folder: folder       });   }}

Notice that example requires redux-thunk middleware to dispatch those actions.

Then you can get access to bookmark with id in the folders reducer

function folderReducer(state = [], action) {  if(action.type === 'ADD_BOOKMARK') {     return state.map(folder => {       if(folder === action.folder) {         return Object.assign({}, folder, {children: [...folder.children, action.bookmark.id]}       }       return folder;     })  }  //another reducer code  return state;} 


Reducers are just manipulating your store's instance. You may the current snapshot of your state using getState()