Sitecore / jss

Software development kit for JavaScript developers building web applications with Sitecore Experience Platform
https://jss.sitecore.com
Apache License 2.0
261 stars 275 forks source link

Export SitecoreContextReactContext #224

Closed jbreuer closed 5 years ago

jbreuer commented 5 years ago

Currently it's possible to get the Sitecore Context by using withSitecoreContext(): https://jss.sitecore.com/docs/client-frameworks/react/sample-app#sitecore-context-access

This works in most situations, but sometimes you don't want to wrap your component with this HOC. For example when you are creating a custom hook.

By exporting SitecoreContextReactContext you can use the new useContext hook: https://reactjs.org/docs/hooks-reference.html#usecontext

Then the following should work:

import { useContext } from 'react';
import { SitecoreContextReactContext } from '@sitecore-jss/sitecore-jss-react';
const sitecoreContextFactory = useContext(SitecoreContextReactContext);
const pageEditing = sitecoreContextFactory.getSitecoreContext().pageEditing;
kamsar commented 5 years ago

Longer term would it be a better solution to export a custom hook to expose this that wrapped useContext?

jbreuer commented 5 years ago

Yes for the longer term a custom hook would be better.

sc-dawidrutkowski commented 5 years ago

I did some basic tests and that change looks valid. The associated pull request has been merged.

peterswallow commented 3 years ago

Any idea when or if this will be released?

ambrauer commented 3 years ago

@peterswallow This has been released since JSS 12.0.0, as well as a hook useSitecoreContext introduced with JSS 16.0.0. So you can now do something like:

import { useSitecoreContext } from '@sitecore-jss/sitecore-jss-react';
const { sitecoreContext } = useSitecoreContext();
const pageEditing = sitecoreContext.pageEditing;
peterswallow commented 3 years ago

@ambrauer I'm using 12.0.0 but SitecoreContextReactContext doesn't appear to be exported...unless I'm looking in the wrong place.

ambrauer commented 3 years ago

@peterswallow How are you attempting to use? e.g. import { SitecoreContextReactContext } from '@sitecore-jss/sitecore-jss-react'; should work. See export in version 12.0.0 here.

kevinolivar commented 3 years ago

Hi there,

I am using withSitecoreContext({ updatable: true }) in one of my UI components. The whole app is wrapped within a .

However, when I navigate around the context seems not being updated...only when I refresh the page. I also tried using useSitecoreContext. Same result.

Idea?