Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logical Error in "prepare callback" example. #4777

Closed
zaladeokin opened this issue Feb 23, 2025 · 0 comments
Closed

Logical Error in "prepare callback" example. #4777

zaladeokin opened this issue Feb 23, 2025 · 0 comments

Comments

@zaladeokin
Copy link

zaladeokin commented Feb 23, 2025

Redux Essentials -> Using Redux data

There is a logical error in the features/posts/postsSlice.ts example of "preparing payload" section of Part 4: Using Redux Data tutorial. The prepare callback function should receive only one parameter—the action object from the action creator. However, the example incorrectly passes two arguments, causing an error.

Image

Below are my suggested solutions to fix this bug:

#Solution 1:

interface PrepareArgument {
  title: string;
  content: string;
}

const postsSlice = createSlice({
  name: 'posts',
  initialState,
  reducers: {
    postAdded: {
      reducer(state, action: PayloadAction<Post>) {
        state.push(action.payload)
      },
      prepare({title, content}: PrepareArgument) {
        return {
          payload: { id: nanoid(), title, content }
        }
      }
    }
    // other reducers here
  }
})

##Solution 2:

interface PrepareArgument {
  title: string;
  content: string;
}

const postsSlice = createSlice({
  name: 'posts',
  initialState,
  reducers: {
    postAdded: {
      reducer(state, action: PayloadAction<Post>) {
        state.push(action.payload)
      },
      prepare(postActionObj: PrepareArgument) {
        return {
          payload: { ...postActionObj, id: nanoid()}
        }
      }
    }
    // other reducers here
  }
})
@aryaemami59 aryaemami59 pinned this issue Feb 26, 2025
@aryaemami59 aryaemami59 unpinned this issue Feb 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant