Error importing SendInBlue in my NodeJS app?

I am refactoring my Node app to use ES6 import modules instead of requiring in files.

I am unable to figure out how to make this work with my e-mail package SendInBlue because I get the error.

TypeError: Cannot read properties of undefined (reading ‘ApiClient’)

Before I was using “import { SibApiV3Sdk } from “sib-api-v3-sdk” but I got the error:

SyntaxError: Named export 'SibApiV3Sdk' not found. The requested module 'sib-api-v3-sdk' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'sib-api-v3-sdk';
const { SibApiV3Sdk } = pkg;

^ So this is why I am using the current import code below, which is not working either?

How can I get this to work?

CODE

import pkg from "sib-api-v3-sdk"
const { SibApiV3Sdk } = pkg"
const defaultClient = SibApiV3Sdk.ApiClient.instance
const apiKey = defaultClient.authentications["api-key"]
apiKey.apiKey = process.env.SEND_IN_BLUE_API_KEY
import secretCodeHtml from "../templates/secretCodeEmail.js"

const sendSecretCodeEmail = (text) => {
  var apiInstance = new SibApiV3Sdk.TransactionalEmailsApi()
  var sendSmtpEmail = new SibApiV3Sdk.SendSmtpEmail()
  sendSmtpEmail = {
    sender: { email: senderEmail },
    to: [
      {
        email: recipientEmail,
        name: recipientEmail,
      },
    ],
    subject: emailSubject,
    htmlContent: text,
  }
  apiInstance.sendTransacEmail(sendSmtpEmail)
}

export default sendSecretCodeEmail

ERROR

file:///Users/app/git/app-node-api/src/emails/create/sendSecretCodeEmail.js:4
const defaultClient = SibApiV3Sdk.ApiClient.instance
                                  ^
TypeError: Cannot read properties of undefined (reading 'ApiClient')
    at file:///Users/app/git/app-node-api/src/emails/create/sendSecretCodeEmail.js:4:35
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)

ReferenceError: reload is not defined

Basically my first error was TypeError: require(...) is not a function, so I immediately put a ; at the end of require("./handlers/slashcommands"). But then I come home with this error: ReferenceError: reload is not defined. This is after I put ; after my requirment.
I’m mainly worrying about this part:

client.slashcommands = new Discord.Collection()

client.loadSlashCommands = (bot, reload) => require("./handlers/slashcommands");
(bot, reload)
client.loadSlashCommands(bot, false)

Any help would be appreciated!

React Native Stack Navigation Hopping Multiple Pages

I am building a react native app and I’m quite confused about how the page navigation is occurring. I seem to have a problem where my navigation is skipping a page.

<NavigationContainer>
      
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen 
          component={HomeScreen}
          name="Home"
        />
        <Stack.Screen 
          component={FirstScreen}
          name="First"
        />
         <Stack.Screen 
          component={AssignWorkoutScreen}
          name="Third"
        />

        <Stack.Screen 
          component={SecondScreen}
          name="Second"
        />
      </Stack.Navigator>
    </NavigationContainer>

My goal is to achieve the following navigation I want to go from home -> First Screen -> 2nd Screen. However, I run into the issue that when I click the first screen it immediately jumps the first screen to the second one.

Code for Home:

class HomeScreen extends React.Component {
    render() { 
        return (
          <View>
            <Button
              title="First"
              onPress={() => this.props.navigation.push("First")}
            />
            
          </View>
        );
    }
}

Code for First Screen:

class FirstScreen extends React.Component {
  render() {
    return (
        <ScreenContainer>
        ...
            <Button
            title='hey'
            onPress={this.props.navigation.navigate("Second")}/>
        ...

      </ScreenContainer>
 
    );
  }
}

Thank you for all your help!

Question Concerning Google Analytics Data API

I got those code while watching this video
https://www.youtube.com/watch?v=teL_9dJDvRw
which provide me with this code, but my login button is not showing, and I think that is caused by “gapi-loaded” is not working
someone have any solution with this?

<title>index.html</title>
 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>Top Shelf Distillers Staff</title>
    <!-- Icon -->
    <link
      rel="icon"
      href="https://cdn.shopify.com/s/files/1/2256/4539/files/top-shelf-distillers-store-2.svg?v=1634904798"
      type="image/x-icon"
    />
    <!-- Font Awesome -->
    <link
      rel="stylesheet"
      href="https://use.fontawesome.com/releases/v5.11.2/css/all.css"
    />
    <!-- Google Fonts Roboto -->
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap"
    />
    <!-- MDB UI KIT -->
    <link rel="stylesheet" href="css/mdb.min.css" />
    <!-- Custom styles -->
    <style></style>
  </head>

  <body style="background-color: hsl(0, 0%, 96%)">
    <!--Main Navigation-->
    <header class="mb-10">
      <!-- Navbar-->
      <nav
        class="navbar navbar-expand-lg navbar-light bg-white shadow-2 fixed-top"
      >
        <div
          class="
            container-fluid
            justify-content-center justify-content-md-between
          "
        >
          <!-- Left elements -->
          <ul class="navbar-nav flex-row align-items-center">
            <li class="nav-item me-3 me-lg-1">
              <a
                class="nav-link d-flex"
                href="https://topshelfdistillers.com/"
                target="_blank"
              >
                <img
                  src="https://cdn.shopify.com/s/files/1/2256/4539/files/top-shelf-distillers-store-2.svg?v=1634904798"
                  height="31"
                  alt=""
                  loading="lazy"
                  class="me-2"
                />
                <span
                  style="
                    font-size: 19px;
                    font-weight: 500;
                    color: hsl(0, 0%, 30%);
                  "
                  >Top Shelf Distillers <span class="text-theme">Staff</span></span
                >
              </a>
            </li>
            <li class="nav-item me-3 me-lg-1">
              <a
                class="nav-link"
                href="https://twitter.com/TSDistillers"
                rel="nofollow"
                target="_blank"
              >
                <span><i class="fab fa-twitter"></i></span>
              </a>
            </li>
            <li class="nav-item me-3 me-lg-1">
              <a
                class="nav-link"
                href="https://github.com/mdbootstrap/mdb-easydata"
                rel="nofollow"
                target="_blank"
              >
                <span><i class="fab fa-github"></i></span>
              </a>
            </li>
          </ul>
          <!-- Left elements -->



          <!-- Right elements -->
          <ul class="navbar-nav flex-row d-none d-md-flex">
            <li class="nav-item me-3 me-lg-1">

              <button
                id="sign-in-btn"
                type="button"
                class="btn btn-primary btn-rounded"
                style="display: none"
                onclick="signIn()"
              >
                Login
              </button>
            </li>

            <li class="nav-item me-3 me-lg-1">
              <button
                id="sign-out-btn"
                type="button"
                class="btn btn-primary btn-rounded"
                style="display: none"
                onclick="signOut()"
              >
                Logout
              </button>
            </li>

            <li class="nav-item me-3 me-lg-1">
              <button
                type="button"
                class="btn btn-primary btn-rounded"
                style="display: none"
                onclick="loadData()"
              >
                Load Data
              </button>
            </li>

            <li class="nav-item me-3 me-lg-1">
              <a
                href="https://mdbootstrap.com/"
                target="_blank"
                class="btn btn-danger btn-rounded mx-2 d-none d-lg-inline-block"
                ><i class="fas fa-cubes me-2"></i>MDB UI KIT</a
              >
            </li>
          </ul>
          <!-- Right elements -->
        </div>
      </nav>
      <!-- Navbar -->
    </header>
    <!--Main Navigation-->

    <!--Main layout-->
    <main>
      <div class="container">
        <!--Section: Design Block-->
        <section class="mb-8">
          <h3 class="mb-7 text-center fw-bold">Last 7 days</h3>
          <div class="row">
            <div class="col-md-4 mb-4 mb-md-0">
              <!-- Card -->
              <div class="card">
                <div
                  class="
                    card-body
                    d-flex
                    justify-content-start
                    align-items-center
                  "
                >
                  <div
                    class="
                      bg-primary
                      text-white
                      rounded-4
                      d-flex
                      justify-content-center
                      align-items-center
                    "
                    style="width: 50px; height: 50px"
                  >
                    <i class="fas fa-users fa-lg"></i>
                  </div>
                  <div class="ms-3">
                    <p class="text-muted mb-1">Users</p>
                    <p class="mb-0">
                      <span id="displayUsers" class="h4 me-2"></span>
                    </p>
                  </div>
                </div>
              </div>
              <!-- Card -->
            </div>
            <div class="col-md-4 mb-4 mb-md-0">
              <!-- Card -->
              <div class="card">
                <div
                  class="
                    card-body
                    d-flex
                    justify-content-start
                    align-items-center
                  "
                >
                  <div
                    class="
                      bg-primary
                      text-white
                      rounded-4
                      d-flex
                      justify-content-center
                      align-items-center
                    "
                    style="width: 50px; height: 50px"
                  >
                    <i class="fas fa-file fa-lg"></i>
                  </div>
                  <div class="ms-3">
                    <p class="text-muted mb-1">Page views</p>
                    <p class="mb-0">
                      <span id="displayPageViews" class="h4 me-2"></span>
                    </p>
                  </div>
                </div>
              </div>
              <!-- Card -->
            </div>
            <div class="col-md-4">
              <!-- Card -->
              <div class="card">
                <div
                  class="
                    card-body
                    d-flex
                    justify-content-start
                    align-items-center
                  "
                >
                  <div
                    class="
                      bg-primary
                      text-white
                      rounded-4
                      d-flex
                      justify-content-center
                      align-items-center
                    "
                    style="width: 50px; height: 50px"
                  >
                    <i class="fas fa-chart-line fa-lg"></i>
                  </div>
                  <div class="ms-3">
                    <p class="text-muted mb-1">Sessions</p>
                    <p class="mb-0">
                      <span id="displaySessions" class="h4 me-2"></span>
                    </p>
                  </div>
                </div>
              </div>
              <!-- Card -->
            </div>
          </div>
        </section>
        <!--Section: Design Block-->
      </div>
    </main>
    <!--Main layout-->

    <!--Footer-->
    <footer></footer>
    <!--Footer-->
  </body>

  <!-- MDB ESSENTIAL -->
  <script type="text/javascript" src="js/mdb.min.js"></script>
  <!-- Google API -->
  <script src="https://apis.google.com/js/api.js"></script>
  <!-- easyData - Google Analtyics -->
  <script type="text/javascript" src="js/easyData-google-analtyics.js"></script>

  <!-- easyData - Fetching data-->
  <script>
    // Your Client ID
    const CLIENT_ID = "1086039826600-2r3481ge270o57vau3kshic6l4vrg4gg.apps.googleusercontent.com";
    

    function loadData() {
      // Your GA property ID
      const propertyId = "323434397";

      const startDate = "7daysAgo";
      const endDate = "today";
      const metrics = [
        { name: "activeUsers" },
        { name: "screenPageViews" },
        { name: "sessions" },
      ];

      const query = {
        dateRanges: [{ startDate, endDate }],
        metrics: metrics,
      };

      runReport(propertyId, query, displayResult);
    }

    function displayResult(response) {
      document.getElementById("displayUsers").innerHTML =
        response.result.rows[0].metricValues[0].value;
      document.getElementById("displayPageViews").innerHTML =
        response.result.rows[0].metricValues[1].value;
      document.getElementById("displaySessions").innerHTML =
        response.result.rows[0].metricValues[2].value;
    }

    // Login buttons

    document.addEventListener("gapi-loaded", (e) => {
      
      if (isSignedIn()) {
        document.getElementById("sign-out-btn").style.display = "block";
        document.getElementById("sign-in-btn").style.display = "none";
        loadData();
        console.log("happen");
      } else {
        console.log("happen");
        document.getElementById("sign-in-btn").style.display = "block";
        document.getElementById("sign-out-btn").style.display = "none";
      }
    });
  </script>
</html>

easyData-google-analtyics.js
// Google Analytics

const GA_SCOPE = “https://www.googleapis.com/auth/analytics.readonly”;
const GA_API_URL = “https://analyticsdata.googleapis.com/$discovery/rest?version=v1beta”;

gapi.load(“client:auth2”, function () {
gapi.auth2.init({ client_id: CLIENT_ID }).then(() => document.dispatchEvent(new Event(‘gapi-loaded’)));
});

function signIn(scope = GA_SCOPE) {
return gapi.auth2.getAuthInstance().signIn({ scope }).then(() => {
setCookie(‘guser-loggedin’, ‘true’, 1);
location.reload();
}, (e) => console.error(e));
}

function signOut() {
return gapi.auth2.getAuthInstance().signOut().then(() => {
setCookie(‘guser-loggedin’, ‘true’, -1);
location.reload();}, (e) => console.error(e));
}

function loadClient(apiPath = GA_API_URL) {
return gapi.client.load(apiPath);
}

function runReport(propertyId, query, cb = function (res) { console.log(res); }, err = function (err) { console.error(err); }) {

return loadClient().then(() => gapi.client.analyticsdata.properties
.runReport({
property: “properties/” + propertyId,
resource: query
})
.then(cb, err));
}

function isSignedIn() {
if (getCookie(‘guser-loggedin’) === ‘true’) return true;
return false;
}

function setCookie(cname = ‘guser-loggedin’, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = “expires=”+d.toUTCString();
document.cookie = cname + “=” + cvalue + “;” + expires + “;path=/”;
}

function getCookie(cname) {
let name = cname + “=”;
let ca = document.cookie.split(‘;’);
for(let i = 0; i

How to determine if sprite is all one color with js

I am dynamically adding spritesheet sprites to a page where a user can select them to add to a grid. I do not have enough sprites yet to completely fill the sprite sheet, so there are a few at the end that are “empty”. Using javascript, can I determine if sprite x,y,16px,16px is empty, so I can omit it? By empty I mean all white(or any color) or transparent.

The sprites are actually added by creating css classes with the background-position. At the time of creation, I have the spritesheet loaded.

Load local file and resize it

I am trying to build trivial website with JS.
I would like to simply load image via button and obtain resized version.
Based on following answers (one and two) I was trying to connect code snippets, however I don’t have any experience with JS.

My approach: http://jsfiddle.net/hp32b5Lc/7/

html:
<input id="upload" type="file" onChange="handleImageUpload()" />
<!-- <img id="display-image" src="" />
 -->
<br>
<br>


<canvas id="canvas" width=300></canvas>

JS:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();

function test() {

    // set size proportional to image
    canvas.height = canvas.width * (img.height / img.width);

    // step 1 - resize to 50%
    var oc = document.createElement('canvas'),
        octx = oc.getContext('2d');

    oc.width = img.width * 0.5;
    oc.height = img.height * 0.5;
    octx.drawImage(img, 0, 0, oc.width, oc.height);

    // step 2
    octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);

    // step 3, resize to final size
    ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,
    0, 0, canvas.width, canvas.height);
}

function handleImageUpload() {

  var image = document.getElementById("upload").files[0];

  var reader = new FileReader();

  reader.onload = function(e) {
    document.getElementById("display-image").src = e.target.result;
  }

  reader.readAsDataURL(image);
  img.src = image;
  img.onload = test()
}

Could you please tell how to do it properly?

eventemitter.on is getting registered and fired mutiple times in when using with sockets.io

I want to call an io.emit(‘eventname’) event of socket.io, when a custom event is triggered in another file in node.js. this happens in response to an HTTP request for a frontend app

moreover, I have created a common event emitter as simple importing and exporting the events was not firing, as expected, between files in node.js

commonEventEmitter.js

var events = require('events')
var em = new events.EventEmitter()

module.exports.commonEmitter = em;

This file receiles the HTTP request and triggers an event i.e ‘newSOS, registered in socket.js file

sosRequest.js

const common = require('../utils/commonEventEmitter')
const commonEvent = common.commonEmitter
    

exports.createSOS = asyncHandler( async (req,res,next) => {
    const { type , location } = req.body
    Request = await SOS.findOne({type : type , createdBy: req.commuter[0].id , 
              status:'Pending'})

     commonEvent.emit('newSOS')
      
     const request = await SOS.create({
    
     type,
     location,
     createdBy,
    })  

    res.status(200).json({
      success:true,
      request
    })

In this file, ‘newSOS’ event is registered and is called many times as on an HTTP request is received.

socket.js

const io = require('socket.io')()
// const eventHandlers = require('./eventHandlers');
const common = require('../utils/commonEventEmitter')
const commonEvent = common.commonEmitter

io.on('connection' , (socket)=>{

commonEvent.on('newSOS' , ()=> {
        console.log('running only once'.bgGreen)
            io.emit('sos_admin' , "just do it")
    })
}


module.exports = io

It’s getting executed multiple times in 1 page. The pattern as follows:

If page is loaded first time it will be executed once.
If page is loaded second time it will be executed twice.
If page is loaded n times it will be executed n times.

and please also tell if my io.on(‘connection’) is getting called multiple times?

Draggable returning null on CreateElement

It’s returning null when the createElement are dropped in their container. But the other elements that are in my html files are dragging correctly except for the elements create with the javascript

window.addEventListener("load", ()=>{
    const Element = document.querySelectorAll( "#Data" )
    const Drop = document.querySelectorAll( "#Drop" )
    const AddBug = document.getElementById( "AddBug" )
    let DraggedItem = null

    AddBug.addEventListener("click", ()=>{
        const BugInput = document.getElementById("BugInput").value
        const Wrapper = document.getElementById("Wrapper")
        const NewDiv = document.createElement("span")
        NewDiv.classList.add("Data")
        NewDiv.setAttribute("id", "Data")
        NewDiv.setAttribute("draggable", "true")
        NewDiv.innerText = BugInput
        Wrapper.append(NewDiv)
    })
    
    for( let i=0; i<Element.length; i++ ){
        const Item = Element[i]

        Item.addEventListener("dragstart", () =>{
            console.log("DragStart")
            DraggedItem = Item
            console.log(DraggedItem)
            setTimeout(()=>{ Item.style.display = "none" },0)
        })
        Item.addEventListener("dragend", ()=>{
            console.log("dragend")
            setTimeout(()=>{
                DraggedItem.style.display = "block"
                DraggedItem = null
            },0)
        })

        for ( let j=0; j<Drop.length; j++ ){
            const list = Drop[j]

            list.addEventListener( "dragover", ( e )=>{ e.preventDefault() })
            list.addEventListener( "dragenter", ( e )=>{ e.preventDefault() })
            list.addEventListener( "drop", ()=>{ list.append(DraggedItem) })
        }
    }

})

How can I make my react search engine to accept both upper and lower case letters?

Hi there my react application is a todolist and has a search engine to filter notes, currently it works if you search for the note but in lower case, how could I make it accept both upper and lower case?

For example, for the javaScript note, it would find it whether I put JAVAscrIPT or jAVAscriPT.

This is my code

const App = () => {
  const [notes, setNotes] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [showNote, setShowNote] = useState(true); //eslint-disable-lint

  const addNote = (inputText, text) => { 
    const date = new Date();
    const newNote = {
      id: nanoid(),
      title: inputText,
      text: text,
      date: date.toLocaleString()
      
    }
    const newNotes = [newNote, ...notes];
    setNotes(newNotes)
  }
  const filterNotes = notes.filter((noteText) => noteText.title.toLowerCase().includes(searchText)); 

//rest of code

A greeting and thanks in advance!

How can I display a popup when I click on a button using react?

How can I display a pop-up container when I click on a button using react. I am creating a find me page and I’d like to display a popup specific to the options I select using react

    import React from 'react';

    import {SubHeading} from '../../components'
    import {images} from '../../constants'
    import './FindUs.css'
    import Select from 'react-select';

    const options = [
    { value: 'lagos', label: 'Lagos' },
    { value: 'kwara', label: 'Kwara' },
    { value: 'abuja', label: 'Abuja' },
    { value: 'imo', label: 'Imo' },
    { value: 'kano', label: 'Kano' },
    ]

    const FindUs = () => (
    <div className="app__findus flex__center section__padding">
    <div className="app__findus-text">
      <h1 className="headtext__cormorant">Enjoy tasty meal wherever you are...</h1>
      <SubHeading title="Find us"/>

      <div className="app__findus-dropdown">
        <Select options={options} 
        placeholder="Select state"
        />

        <button className="custom__button">View Outlets</button>
      </div>
    </div>

    <div className="app__findus-img">
      <img src={images.side} alt="side" />
    </div>

    </div>
    );

    export default FindUs;

React/nextjs fetch data on a button click, but the button is in a different component

I have a function in the that fetches the weather data for current location when button is clicked. I want to get this data from the Location component to the pages/index.tsx where I have another components that displays that data.

This is my component structure:

App
  --Layout
    --Header
      --Location (here i fetch the data on click)
    --Home (state)
      --Display 1
        --SubDisplay 1
      --Display 2 

Do I have to pass the data through all the components to the index page? It would be:

  1. UP from Location to Header
  2. UP from Header to Layout
  3. DOWN from Layout to Index page
  4. DOWN from Index page to another components

Is this the best way to handle this?

How to make a post request to WordPress to update images for employees via custom image field using WordPress API

I’m trying to figure out a way to update employee information on a WordPress website. so far i have figured out how to update one user at a time by adding id on the endpoint. how can i update all users at once. I’m also using custom field via ACF

var axios = require('axios');

var data = JSON.stringify({
    "acf": {
        "twitter": "aaaaaaa",
      //"profile_picture": null,
    }
});

var config = {
    method: 'post',
    url: 'http://localhost:8888/sitename/wp-json/wp/v2/team/1111',
    headers: {
        'Authorization': 'Basic dhhdsgbhadG',
        'Content-Type': 'application/json'
    },
    data: data
};

axios(config)
    .then(function(response) {
        console.log(JSON.stringify(response.data));
    })
    .catch(function(error) {
        console.log(error);
    });

This code updates team member 1111 twitter url. so 2 questions

  1. How do I do a post request for images.
  2. How will i make this script update all employee profile pictures at once

the images are stored in a folder with each image url using their names

How to redact data from array?

If I have a weather data, which is an array, like this one below.

const weather = [
{date:'2022-07-18', min_temp:15, max_temp:26, type:'clouds'},
{date:'2022-07-18', min_temp:13, max_temp:27, type:'sun'},
{date:'2022-07-18', min_temp:23, max_temp:31, type:'clouds'},
{date:'2022-07-18', min_temp:19, max_temp:28, type:'rain'},

{date:'2022-07-19', min_temp:21, max_temp:25, type:'rain'},
{date:'2022-07-19', min_temp:17, max_temp:29, type:'rain'},
{date:'2022-07-19', min_temp:14, max_temp:38, type:'rain'},
{date:'2022-07-19', min_temp:9, max_temp:30, type:'clouds'}
]

How can I reduce the array, one data/date, with the min and max temperature from the same date, and type should be the most frequently type from the same date.
It should look like this one below.

const weather = [
{date:'2022-07-18', min_temp=13, max_temp31, type:'clouds'},
{date:'2022-07-19', min_temp=9, max_temp:38, type:'rain'}
]

How to hide tooltip for certain bars in chart.js

I am making a stacked bar that looks like the following:

enter image description here

The spaces you see in between each bar are bars static-sized bars that are the color of the background. I used them because I could not figure out how to add a space between bars in chart.js. I am trying to figure out how to hide the tooltip for the static-sized gray bars. As of right now, my code shows a black tooltip that freezes until I refresh the page when I hover over a gray bar. Here is the code for hiding it so far:

filter: function(tooltipItem) {
    return tooltipItem.dataset.backgroundColor[0] !== "#f5f5f5";
    // if (tooltipItem.dataset.backgroundColor[0] == "#f5f5f5") {
    //     return false;
    // }
    // console.log(tooltipItem.dataset.backgroundColor);
    // return true;
 }

antV chart design legend

please I want to make legend in this chart based on the ‘action’ value.
I just got ‘sell’ for the both lines:
enter image description here
The code:

  const config = {
    data,
    xField: 'createdAt',
    yField: 'price',
    seriesField: 'action',
    yAxis: {
      label: {

        formatter: (v) => `${v}`.replace(/d{1,3}(?=(d{3})+$)/g, (s) => `${s},`),
      },
    },
    
    legend: {
      position: 'top-right',
      itemName: {
        style: {
          fill: '#000',
        },

        formatter: (seriesField) => {
          if (seriesField.value === "1") {
            return 'buy';
          }

          return 'sell';

        },
        //formatter: (name) => name,

      },
    },


  };