I'm having problems with React recognizing a nested state update. I've read through the excellent responses here but still have questions.
I can confirm that the state change is being made and recognized in my components. The only thing I'm not seeing is React updating the tree, which I've read usually means React doesn't recognize my state updates (only looks for shallow copies). But, React does update the tree enough to trigger console.log()
updates in my consumer.
Maybe I'm not binding something in the right spot? My consumer is also pretty intense but otherwise working. Also open to refactoring options.
FilterContext:
import React from 'react';
export const FilterContext = React.createContext();
class FilterProvider extends React.Component {
constructor(props) {
super(props);
this.toggleEuphoric = () => {
this.setState(prevState => ({
...prevState,
emotions: {
...prevState.emotions,
anxious: false,
aroused: false,
calm: false,
cerebral: false,
creative: false,
energetic: false,
euphoric: true,
focused: false,
giggly: false,
happy: false,
hungry: false,
meditative: false,
mellow: false,
noemotion: false,
relaxed: false,
sleepy: false,
talkative: false,
tingly: false,
uplifted: false,
}
}))
},
this.state = {
emotions: {
anxious: null,
aroused: null,
calm: null,
cerebral: null,
creative: null,
energetic: null,
euphoric: null,
focused: null,
giggly: null,
happy: null,
hungry: null,
meditative: null,
mellow: null,
noemotion: null,
relaxed: null,
sleepy: null,
talkative: null,
tingly: null,
uplifted: null,
},
toggleEuphoric: this.toggleEuphoric,
}
}
render() {
return (
<FilterContext.Provider value={ this.state }>
{ this.props.children }
</FilterContext.Provider>
)
}
}
export default FilterProvider;
Filter Consumer:
<FilterContext.Consumer>
{ filterToggle => (
// Check the emotions part of the FilterContext state object
// If all options are null, it means no interactions have taken place
// So we show all results using .map() over the pageContext.productData array coming out of gatsby-node.js
Object.values(filterToggle.emotions).every(item => item === null) ? (
this.props.pageContext.productData.map( (product) => {
return <ProductListItem
desc={ product.shortDescription }
handle={ product.handle }
image={ product.image }
key={ product.id }
productType={ product.productType }
strain={ product.strain }
tac={ product.tac }
tags={ product.tags }
title={ product.title }
/>
})
) : (this.props.pageContext.productData.map( product => {
emotion = Object.keys(filterToggle.emotions).find(key => filterToggle.emotions[key])
return product.tags.forEach( (tag) => {
tag.toLowerCase() === emotion &&
console.log(this),
<ProductListItem
desc={ product.shortDescription }
handle={ product.handle }
image={ product.image }
key={ product.id }
productType={ product.productType }
strain={ product.strain }
tac={ product.tac }
tags={ product.tags }
title={ product.title }
/>
}
)
}))
)}
</FilterContext.Consumer>