Skip to content

Commit

Permalink
[JSS][React] SitecoreContextReactContext.Provider is not working prop…
Browse files Browse the repository at this point in the history
…erly, because value never changes as it is always same class instance (#983)
  • Loading branch information
illiakovalenko authored Apr 28, 2022
1 parent fa2ba4a commit 7b65d25
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions packages/sitecore-jss-react/src/components/SitecoreContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,22 @@ export class SitecoreContextFactory {
};
}

getSitecoreContext() {
getSitecoreContext = () => {
return this.context;
}

subscribeToContext(func: any) {
subscribeToContext = (func: any) => {
this.subscribers.push(func);
}

unsubscribeFromContext(func: any) {
unsubscribeFromContext = (func: any) => {
const index = this.subscribers.indexOf(func);
if (index >= 0) {
this.subscribers.splice(index, 1);
}
}

setSitecoreContext(value: any) {
setSitecoreContext = (value: any) => {
this.context = value;
this.subscribers.forEach((func) => func(value));
}
Expand Down Expand Up @@ -65,9 +65,7 @@ export class SitecoreContext extends React.Component<SitecoreContextProps> {
} else {
this.contextFactory = new SitecoreContextFactory();
}
}

componentDidMount() {
// we force the children of the context to re-render when the context is updated
// even if the local props are unchanged; we assume the contents depend on the Sitecore context
this.contextFactory.subscribeToContext(this.contextListener);
Expand All @@ -79,10 +77,16 @@ export class SitecoreContext extends React.Component<SitecoreContextProps> {
this.contextFactory.unsubscribeFromContext(this.contextListener);
}

/**
* React Context Provider should accept Object instead of
* SitecoreContextFactory class instance
*/
getSitecoreContextValue = () => ({ ...this.contextFactory });

render() {
return (
<ComponentFactoryReactContext.Provider value={this.componentFactory}>
<SitecoreContextReactContext.Provider value={this.contextFactory}>
<SitecoreContextReactContext.Provider value={this.getSitecoreContextValue()}>
{this.props.children}
</SitecoreContextReactContext.Provider>
</ComponentFactoryReactContext.Provider>
Expand Down

0 comments on commit 7b65d25

Please sign in to comment.