开发者

Using a part of complex map from Stores React

Consider this value stored in Zustand/Any Other Store.

productMap: {
   'product-id-abc': {
      info: {
         name: 'Gmail',
         url: 'gmail.com',
         api: 'localhost:8080'
      },
      endpoint: [{
         'url': '/getemail',
         'method': 'GET'
      }],
      users: [{
         firstName: 'Sam',
         email: 'sam@web.com'
      }]
   }
}

So, if need to access any value within the store it is tricky. Consider this case when I need to access the first user of the product with id product-id-abc. Currently I am following this method. However this fails my usecase as when the store is updated it doesn't reflect in the state variable. The following will be my code.

  const productMap = useB开发者_开发百科oundedStore(state => state.productMap);
  const [user, setUser] = useState();

  useEffect(()=>{
     if(productMap[props.productId])
        if(productMap[props.productId].users.length) {
           setUser(productMap[props.productId].users[0]);
        }
  },[[]]) // ---> (1)

The easier way would be to add productMap to dependencies marked with (1) , however is there any better way, like storing it as variables. It would be great if someone could share some better patterns.


If I understood correctly, for retrieving users from storage the easiest way is to use useSelector.

const users = useSelector(state = > state.productMap[props.productId].users)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜