node.jsreactjsreduxreact-reduxcloudkit-web-services

How to authenticate CloudKit JS in react JS or React-Redux JS


I am very new to web development. I have downloaded the CloudKit JS & adding in index.html in script tag. And I made sure it loads before my react-redux bundle JS.

  <script src="/cloudkit.js"></script>
  <script src="/bundle.js"></script>

I have made single class component & I am running authentication on component did mount as follows.

componentWillMount() {
CloudKit.configure({
  containers: [{
    containerIdentifier: '<container ID>',
    apiToken: '<secret api token>',
    environment: 'development'
  }]
});
var container = CloudKit.getDefaultContainer();
container.setUpAuth().then(function(userInfo) {
  if(userInfo) {
            console.log(userInfo);
        } else {
            console.log('need to login');
        }
    });
}

Then I get following errorenter image description here How do I authenticate in React with CloudKit JS?


Solution

  • The 421 is expected: basically this is CloudKit JS checking with the server if the user is signed in. You should still see your log statement 'need to login'.

    You should also:

    Sample code (https://jsfiddle.net/byb7ha0o/4/):

    CloudKit.configure({
      containers: [{
        containerIdentifier: '<container>',
        apiToken: '<token>',
        environment: 'development'
      }]
    });
    const container = CloudKit.getDefaultContainer();
    
    class HelloCloudKitJS extends React.Component {
    
      constructor() {
        super();
        this.state = {
            userInfo: null
        }
      }
    
      componentDidMount() {
        container
          .setUpAuth()
            .then(userInfo => {
            if(userInfo) {
                this.setState({userInfo: userInfo});
              return;
            }
            container
              .whenUserSignsIn()
                .then(userInfo => {
                    this.setState({userInfo: userInfo})
              })  
          })
      }
    
      render() {
        return <div>
          <div>
            <div id="apple-sign-in-button"></div>
            <div id="apple-sign-out-button"></div>
          </div>
        </div>;
      }
    }
    
    ReactDOM.render(
      <HelloCloudKitJS />,
      document.getElementById('container')
    );