简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM