Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useSelector first returns undefined, then returns object

I'm trying to extract data from state. I'm using redux.

const {currentPost } = useSelector(state => state.posts)

I expected to get an object with properties. Instead I get couple of undefined and then I get an object. These undefined on the start causes that I can't destructure further like const {currentPost: {id} } = useSelector(state => state.posts)and returns error that it can't read property of undefined. These posts are obtained by API.

I've tried to workaround it by use a function which checks if this currentPost is undefined and then pass null into these properties. However it's not suitable for project and this solution is error prone.

like image 328
ArcMech Avatar asked Nov 25 '19 19:11

ArcMech


1 Answers

As I get more experience I want to share my knowledge for future young frontend developers

I'm using redux-toolkit https://redux-toolkit.js.org/ These undefined values are from async operations, so its their behaviour that sometimes before promise is completed return undefined value.

To overcome it and write stable code there is a need to add default values. In redux-toolkit you can use

const slice = createSlice({
  name: 'posts',
  initialState: {
    currentPosts: {
      value: {
        name: ''
      }
    },
    posts: []
  },
  reducers: {
    ...reducers
    },
})

In that case you'll get Object currentPosts, which is not undefined.

like image 174
ArcMech Avatar answered Oct 05 '22 23:10

ArcMech