I have a component and corresponding actions and reducers for it. In actions, when I am doing the API call, I make the call like this
export const getData = () => {
return axios.post(url, data, headers){
.then((response)=>{
const messages = response.data.map({has_favourited_message: isFavourited}) //I am doing this since ESLINT throws errors
=>({isFavourited})
})
return messages;
}
}
In the component, I am using it like this
class ProductView extends React.Component {
constructor(props) {
super(props);
this.state = { page: 0, imageUrls: [], isFavourited: props.product.isFavourited || props.product['has_favourited_message']
}
render(){
return null;
}
}
In the reducer, I have
case GET_DATA:
return {
...state,
data: state.data.map((item) => {
if (item.id !== action.payload.id) return item;
return { ...state, ...item, has_favourited_message: action.payload.isFavourited }; //Here I don't want to add any extra key so I am using the original key only as I am dispatch the above action to multiple reducers so it would become inconsistent if I change the key
}),
};
I am using props.product.isFavourited || props.product.'has_favourited_message'
props.product.isFavourited || props.product.'has_favourited_message'
because ES-Lint won't allow me to use like this ------ props.product['has_favourited_message']
. I believe that there is a better way of doing this without changing the key in reducer or adding comment eslint-disable-line.
I am new to desructuring. Please help.
You can always check if property is present or not by hasOwnProperty('property1') Later you can use
props.product.hasOwnProperty('has_favourited_message') ?props.product.has_favourited_message : 'There is no favourited message'
I hope i would help
You map function syntax is incorrect, you need a wrapping ()
before destructuring map arguments
.then((response)=>{
const messages = response.data.map(({has_favourited_message: isFavourited}) => ({isFavourited})
return messages;
})
Also instead of props.product.'has_favourited_message'
, you should write props.product.has_favourited_message
since props.product.'has_favourited_message'
is an invalid syntax
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.