Save discount as a shop metafield in Node.js React app

Hey, I’m following this tutorial on Building your user interface with Polaris and want to save the discount value as a Shop metafield on handleSubmit() inside pages/annotated-layout.js .

As a total newbie to this react.js + node architecture, i have no clue how to save the metafield using Admin API on handleSubmit()

It would be great if anyone can help me with an example logic/code.

Thanks

So after a week of rigorous battle with the code and the API , i finally figured out how to save the discount as a metafield.

I also encountered a lot of errors including 405, 500, 501

I’m sharing the solution here, so that it will helpful for anyone Or some Expert can suggest a better way to do the same.

Client side

const options={headers:{"Content-Type":"application/json"}};

axios.post("/metafield",
          {metafield:{namespace:"shop",key:"discount",value:this.state.discount,value_type:"string"}},options)
          .then(o=>{console.log(o)},o=>{console.log(o)});

Server side

router.post("/metafield", koaBody(), async (ctx) => {
    try {
      const data = JSON.stringify(ctx.request.body);
      const apikey = ctx.cookies.get("accessToken");
      const shop = "xxxxxxxxxxxx.myshopify.com";

      const response = await fetch(
        `https://${shop}/admin/api/2020-04/metafields.json`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-Shopify-Access-Token": apikey,
          },
          body: data,
        }
      );
      const responseJson = await response.json();
      ctx.body = responseJson;

    } catch (error) {
      console.log(error);
    }
  });

Hi @jojo_1 , thanks for posting your solution. I have two questions.

  1. How does the access token get into your cookies?
  2. Is it safe to have the access token available in the cookies like that?

Thanks,

Refer https://stackoverflow.com/questions/58347894/shopify-app-access-token-how-to-make-it-more-secure