React Redux Toolkit Tips: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 13: Line 13:
export const selectAllPosts = (state) => state.posts;
export const selectAllPosts = (state) => state.posts;
</syntaxhighlight>
</syntaxhighlight>
=Tip 1 Prepare Callback=
=Tip 2 Prepare Callback=
We started with this where we pass an object in the action
We started with this where we pass an object in the action
<syntaxhighlight lang="js" highlight="5-7">
<syntaxhighlight lang="js" highlight="5-7">
Line 48: Line 48:
   }
   }
})
})
</syntaxhighlight>
=Tip 3 Unwrap=
Adding try catch to dispatch will unwrap the returning result which is a promise
<syntaxhighlight lang="js">
try {
  setAddRequestStatus('pending')
  dispatch(addNewPost({title, body:content, userId }).unwrap()
  setTitle('')
  setContent('')
  setUserId('')
} catch(err) {
  console.error('Failed to save', err)
} finally {
  setAddRequestStatus('idle')
}_
</syntaxhighlight>
</syntaxhighlight>

Revision as of 04:59, 31 December 2022

Introduction

Taken from YouTube https://www.youtube.com/watch?v=NqzdVN2tyvQ

Tip 1 Probably should know this

Instead of using

const posts = useSelector((state) => state.posts);

We can use

// In the component
const posts = useSelector(selectAllPosts)
// In the Slice
export const selectAllPosts = (state) => state.posts;

Tip 2 Prepare Callback

We started with this where we pass an object in the action

const postsSlice = createSlice({
    name: 'posts',
    initialstate,
    reducers: {
       postAdded(state, action) {
           state.push(action.payload)
       }
    }
})

They like to provide an API parameter to minimize the work and make a prepare function

const postsSlice = createSlice({
    name: 'posts',
    initialstate,
    reducers: {
       postAdded: {  
           reducer(state, action) {
           state.push(action.payload)
       },
       prepare(title, content) {
           return {
              payload: {
                id: nanoid(),
                title,
                content 
              } 
           }
       }
    }
  }
})

Tip 3 Unwrap

Adding try catch to dispatch will unwrap the returning result which is a promise

try {
  setAddRequestStatus('pending')
  dispatch(addNewPost({title, body:content, userId }).unwrap()

  setTitle('')
  setContent('')
  setUserId('')
} catch(err) {
  console.error('Failed to save', err)
} finally {
  setAddRequestStatus('idle')
}_