spreespree-auth-devise

How to get Token with spree API v2 SDK


I have a Spree 3.7 app and am trying to use the storefront API v2 to get a token. I've been recommended to use their SDK, but I'm failing to understand how to use the SDK

Example below:

Identifies a guest user's cart and order.

const response = await client.cart.create()

const orderToken: string = response.data.attributes.token

It isn't clearly stated where the response.data.attributes.token comes from or how to get it.

Does anyone have an example how to use the SDK to get an API token? Currently not able to do so. It's stated that using /cart I can get a guest token button trying to get a response ends with a 404

const orderToken: string = response.data.attributes.token returns data as unkown. Where do I get the data value from?

  import { makeClient } from '@spree/storefront-api-v2-sdk/dist/client';


async function asyncCall() {
  console.log('calling');

  // When using the SDK in a <script> tag or as part of a Webpack bundle
  // targeted for the browser, instead use:
  // import { makeClient } from '@spree/storefront-api-v2-sdk/dist/client'

  const client = makeClient({
    host: 'https://stern-telecom-react-salman15.c9users.io/'
  });

  console.log(client)

  const createCart = await client.cart.create()


  const orderToken = response.data.attributes.token

  const addToCart = await client.cart.addItem({ orderToken }, {
    variant_id: '1',
    quantity: 1
  })

  console.log('orderToken',orderToken,'createCart',createCart);
  // expected output: 'resolved'
}

asyncCall();

Solution

  • I've managed to get the API token using the SDK by adding .succes() before calling the data

    const client = makeClient({
       host: 'yourwebsite or localhost:3000'
     });
     console.log('cliet',client);
    
    const cartCreateResponse = await client.cart.create()
     console.log('cartCreateResponse',cartCreateResponse.success().data);
    
    
    const orderToken = cartCreateResponse.success().data.attributes.token
     console.log('orderToken', orderToken);
    
     const addToCart = await client.cart.addItem({ orderToken }, {
       variant_id: '1',
       quantity: 1
     })