how to use function this.state to send variable to other components on react

i still beginner for react and i want to use this function this.state to send variable to other component

here is my code. i build file name App.js

class Login extends React.Component {

  constructor(props) { 
    super(props);
    this.state = {
        skipButton: false
    };
    
  }

  changeSkipPage = () => {
    this.setState = {skipButton: true},
    <Home handleClick={this.setState.skipButton} />
  }
  
  render() {
    return (  
        <div>   
            <a onClick={this.changeSkipPage}>
                <span> Skip Login</span>
            </a> 
        </div>  
      )
  }
}

 
class Welcome extends React.Component { 
    render() {
      return (  
          <div>   
              Welcome World
          </div>  
        )
    }
  }

 
class Home extends React.Component {
  constructor(props) {  
   
    super(props); 
   
    console.log(props)
    
  } 

  render() {   
    return ( 
        // set condition if can get variable handleClick is true. will have condition to change other page 
        // if(variable handleClick is true) {
        //     will call page <Welcome />
        // }else{
        //     still login page
        // }
      )
  }
}

so what was i tried to do is, class Home is combine component from class Login and class Welcome. first display is class Login if condition is user click skip button, class Home the display will change to class Welcome

but above code not work. it not send the variable from class Login when click skip button to class Home

please help.

Why is button.onclick submitting only once?

I’m working on a basic recipe selector project. I want to make this button display a new recipe every time it’s clicked, but right now it executes only once and then remains static.

<button onclick = "displayInfo()" id = "getRecipe">What should I cook?</button>

<div id ="recipeInfo"> Placeholder </div>

<script>
    let displayInfo = function() {
      let finalText = `How to cook ${recipes[selectedRecipe]}; 
        First, prep this list of ingredients: ${ingredients[selectedRecipe]} 
        Then, ${steps[selectedRecipe]}`   
    
      document.getElementById("recipeInfo").innerHTML = finalText;
    }
</script>

Basically, I want to make this button change the recipeInfo div every time it’s clicked. What’s preventing this?

Node.js – Using input parsed from form to route to a specific URL

I am trying to allow a user to enter their name and have it added to the URL.

for example if the users input is John it redirects the user to “/profile/John”

So far I have tried to define a variable name from the parsed input from my html form.

html code;

<h4>Search for your profile by entering your name below.</h4>
<form class="" action="/" method="post">
  <input type="text" name="name" placeholder="Enter your name">
  <button type="submit" name="button">Search</button>
</form>

Node code;

app.get('/',function(req,res){
    var name = String(req.body.name);
});
app.post("/profile/:" + name, (req,res)=>{
  var data = {
    age: 19,
    job: 'Student',
    hobbies: ['Fishing','Video games','Anime','Basketball']
  };

  res.render('profile',{name: req.params.name, data: data});
});

But I get this error;

                     ^
app.get('/profile/:' + name, (req,res)=>{
                       ^


ReferenceError: name is not defined

if statement not respecting character ‘””‘ quotes at all

if statement not respecting character ‘””‘ quotes at all:

I am trying this if statement:

if((character === ' ' && currentlyFormingPhrase.length === 0) || (character === '""' && currentlyFormingPhrase.length === 0))

even variations like this:

if((character === ' ' && currentlyFormingPhrase.length === 0) || (character === '""' && currentlyFormingPhrase.length === 0))

if((character === ' ' && currentlyFormingPhrase.length === 0) || (character === "''" && currentlyFormingPhrase.length === 0))

if((character === ' ' && currentlyFormingPhrase.length === 0) || (character === "''" && currentlyFormingPhrase.length === 0))

Don’t work…

I still get outputs like this:

"” and that being around good people"

But I need:

"and that being around good people"

Stubbing two methods exported from the same file using Sinon

I’m a newbie to JavaScript and need help in unit-testing my code.
There is an existing file F1.js whose methods I’m using in my implementation. The file looks like this:

F1.js :


function A({p1, p2}, callback) {

}

function B(q1, q2) {

}

module.exports = A;
module.exports.B = callbackify(B);

My file Sol.js uses these functions as,

Sol.js:


const A = require('/F1');
const {
  B 
} = require('/F1');


somefunction() {



   B( param1, param2, (err, result) => {
      A( {anotherParam, result}, 
         function (err, result2) {
             // do something with result2

         }
      ) 
   })

}

I’m trying to unit test the method somefunction and struggling with the stubbing. Here is how I mock the functions

Sol_Test.js

B_stub = sinon
      .stub()
      .callsFake((param1, param2, callback) => callback(null, result1));

A_stub = sinon
      .stub()
      .callsFake(({ param1, param2 }, cb) => cb(null, result2));

return proxyquire(
   A_stub,
   B : B_stub,
)

I’m getting the error : B is not a function

Disable JS commands that hack in youtube in the browser- generator watchs

I do not know if this is the right place to ask ..
But I need help modifying and deleting a script in my hacked browser or using my youtube identity and generating tens of thousands of views from my account there.

It started when I suddenly heard a song in the background without turning it on, there were no controls and it did not appear that the song was playing.
Then I went down in history on YouTube and saw thousands of views of videos I had never seen.

I started researching the matter and discovered that my browser had a suspicious YouTube profile in the JavaScript that had a window on it – even if it was not a YouTube site.

And it’s just running on my computer thousands of secret viewing commands, I’ve turned to youtube tech support and they have no idea and their customer service is really bad.

Then I went to the source of the page and discovered that there are hundreds of virtual machine entries from my computer with a hidden IP address and all sorts of JS files running at me at any moment with errors.
And the Verbose reached more than 20,000.

enter image description here

select javascript VM profiler i want rmove it!

enter image description here

also..

I did a full browser reset
And I left only 4 active plugins in Edge
I deleted all cookies in the browser,
I downloaded computer cleaning software and anti-spyware software
And later I also reset the computer .. and it still went on.

Again to note that on the other computer with the same Google and Microsoft account that are connected to the same network and linked to the same account with the browser – this activity is not present.

Lowerbit did not find this malicious feature.

I want to track the activity of this viewer – but the activity code disappears in an instant and it’s hard to see exactly – but no doubt suspicious activity can be detected.

I found about the plugin that took over my computer frankly in

edge: // serviceworker-internals /? devtools

He is back

enter image description here

I’ve seen so much more activity behind the scenes of the browser that it’s crazy!

I’m already really desperate and I do not know what to do!

I would appreciate your assistance

enter image description here

Please I can no longer stand the slowdown of the computer
And in the weird views I have on YouTube!

Using JQuery in a MEN Stack Application

I am building an application using Mongo, Express, Node.js. I am trying to embed some JQuery inside an .ejs file so that when the user upvotes a post, the score for that post is incremented (or decremented). I read this post how to use jQuery installed with npm in Express app?. I have included the <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> in my header. But when I execute my code I get an error that ‘$ is not defined’. Here is the relevant portion of the code:

              <div class="carousel-inner">
                <!-- Carousel item represents each slide -->
                <div class="carousel-item active">
                  <div class="container">
                    <div class="row align-items-center">
                      <h2>
                        Use Arrow Buttons to Scroll DOWN and UP
                      </h2>
                    </div>
                  </div>
                </div>

                <%   
                  var max = questions.length
                  for (var i = 0; i < max; i++) {
                %>
                <div class="carousel-item" style="text-align: justify" >
                  <div class="row">
                    <h2><%= questions[i].title %></h2>
                    <p><%= questions[i].body %></p>
                    
                  </div>
                  <div class="row" style="width: 100%; height: 90px; white-space: nowrap; overflow-x: auto;">
                    <p style = "display: inline-block; width: 70%; height: 100%;"><strong>Posted by: </strong><%= questions[i].userid.username %> on <%= questions[i].datePosted.toDateString() %> </p>
                    <button id="submitButton" style = "display: inline-block; width: 30%; height: 50%; border-radius: 5px; background-color:darkcyan" type="submit">View Responses</button>
                  </div>
                  <div class="row" style="width: 100%; height: 90px; white-space: nowrap; overflow-x: auto;">
                    <button style = "display: inline-block; width: 25%; height: 50%; border-radius: 5px" id="minus">-</button>
                    <button style = "display: inline-block; width: 25%; height: 50%; border-radius: 5px" is="plus">+</button>
                    <%  relevance = questions[i].upvotes %>
                    <p style = "display: inline-block; width: 50%; height: 100%;" id = "score"><strong>  Score: </strong> <%= relevance %></p>
                  </div>
                  <%
                    var myBoolean = 0;
                    
                    $("#plus").click(function(){
                    
                      if (myBoolean == 0) {
                      relevance++;
                      myBoolean = 1;
                      }
                      $("#score").text(relevance);
                    });
                    
                    $("#minus").click(function(){
                      if (myBoolean == 0) {
                        relevance--;    
                      myBoolean = 1;
                      }
                      $("#score").text(relevance);
                    });
                    
                    %>
                </div>
                <% } %>
              </div>

I also want to update my mongoDB database with the updated score using Mongoose, but right now I am just trying to get the basic increment / decrement to work. I tested all the code OTHER THAN the snippet that starts with <% var myBoolean … %>. It all works. Its just when I try to use the JQuery that this does not work. Can someone point me in the right direction?

How to send Json to PHP with JS

I’m trying to send a Json object to PHP, but when I run the PHP code it doesn’t receive anything. I get the Json from transforming an excel file into Json and from there I want to send it to PHP to process it and save it in the database. The problem is that the Network does not send me anything:

below my code:

//this code is to convert excel file in json
let selectedFile;

document.getElementById('importBUDid').addEventListener('change', (event)=>{
    selectedFile = event.target.files[0];
});

document.getElementById('uploadBud').addEventListener('click', ()=>{
    let jsonObj;
    if (selectedFile) {
        let fileReader = new FileReader();
        fileReader.readAsBinaryString(selectedFile);
        fileReader.onload = (event)=>{
            //console.log(event.target.result);
            let dato = event.target.result;
            let workbook = XLSX.read(dato, {type:"binary"});
            //console.log(workbook.Strings);
            workbook.SheetNames.forEach(sheet => {
                let rowObject = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheet]);
                //console.log(rowObject);
                jsonObj = rowObject;
            });
            //console.log(jsonObj);
            testBud(jsonObj);
            
        }
    }
    
}); 
//this code is to send the json object to PHP
function testBud(dt1){
    const dt = JSON.stringify(dt1)
    //console.log(dt);


    const data = new FormData();
    const jsonBlob = new Blob([dt], {type: "application/json"});
    data.append("data", jsonBlob);
    //console.log(data.data);
    console.log(data.data);
    fetch("model/importBud.php", {
    method: "POST",
    body: data.data,
    /* headers:{
      'Content-Type': 'application/json'
        }, */
    }).then(resp => {
    if(!resp.ok) {
        const err = new Error("Response wasn't okay");
        err.resp = resp;
        throw err;
    }
    console.log(resp);
    }).catch(err => {
    console.error(err);
    });
}

PHP below

$obj = $_POST['data'];

if ($obj != "") {
    echo "lleno";
}else{
    echo "vacío";
}

populating cell with data from a different table

I am using a low code app development program, whilst being good and helping make things slightly faster, it has quite a few limitations.

Simplified
The app is essentially used to store jobs… there are different tables, one for suppliers, another for customers etc and they are linked to the main table via Foreign Keys.

When I chose the customer, for example, in the job table, it then replaces the customer name with a number which is the primary key (ID) fro the customer table…

I have tried using generated columns and adding a query like SELECT 'Name' from TableB where id = fk_TableA_TableB but it does not work, I have since found that it is not possible to query other tables via expressions.

The other issue I have is that I cannot create a view because the app requires a Primary key which the view does not offer

What I am looking for is…

So TableA looks like

Name fk_TableA_TableB
Job 1 2
Job 2 1

TableB

id Name
1 Joe
2 John

The Result I would linke to acheive is an extra row at the end of TableA which gives the value of TableB based on the foreign key

Name fk_TableA_TableB TableB
Job 1 2 John
Job 2 1 Joe

An expression does not seem to work…

Is there a way I can use javascript to achieve a similar outcome…

Onchange of cellA update CellB with Customer_Name from tableA where Foreign_Key = id

IS this achievable?

How to update buffers between consecutive runs of a pipeline?

It seems to me that I have to create a new GPUCommandBuffer every time I want to load new input values (either uniform or storage) into the GPU buffers.

I tried loading new data into an existing staging buffer, with mapAsync(), and running an existing command buffer which starts with a copyBufferToBuffer(). But the kernel only sees the old data, the new buffer never gets copied.

If instead I create a new GPUCommandBuffer, identical to the old one, then it sees the new data.

What am I missing?

Here is the code. I’m using passEncoder.endPass() because I’m on Firefox trunk, if you’re on Chromium you may have to replace it with passEncoder.end()

if (!navigator.gpu) alert('WebGPU not supported.')

const adapter = await navigator.gpu.requestAdapter()
if (!adapter) alert('Couldn’t request WebGPU adapter.')

const device = await adapter.requestDevice()
if (!device) alert('Couldn’t request WebGPU device.')

// ------------------------------------------ GPU Kernel ------------------------------------------

// language=WGSL
const code = `
  @group(0) @binding(1) var<storage, read>       b1_input: array<f32>;
  @group(0) @binding(2) var<storage, read_write> b2_output: array<f32>;

  @compute @workgroup_size(64)
  fn main(
    @builtin(global_invocation_id) global_id: vec3<u32>,
  ) {
    if (global_id.x >= arrayLength(&b1_input)) {
      return;
    }
    b2_output[global_id.x] = b1_input[global_id.x] * 10.0;
  }
`

// ---------------------------------------- Create buffers ----------------------------------------

const { MAP_READ, MAP_WRITE, COPY_DST, STORAGE, COPY_SRC } = GPUBufferUsage

const b1_input_size = 4 * 10
const b1_input_gpu = device.createBuffer({ size: b1_input_size, usage: STORAGE | COPY_DST })
const b1_input_stage = device.createBuffer({ size: b1_input_size, usage: MAP_WRITE | COPY_SRC })

const b2_output_size = 4 * 10
const b2_output_gpu = device.createBuffer({ size: b2_output_size, usage: STORAGE | COPY_SRC })
const b2_output_stage = device.createBuffer({ size: b2_output_size, usage: MAP_READ | COPY_DST })

// --------------------------------------- Create pipeline ----------------------------------------

const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'read-only-storage' } },
    { binding: 2, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'storage' } },
  ],
})

const bindGroup = device.createBindGroup({
  layout: bindGroupLayout,
  entries: [
    { binding: 1, resource: { buffer: b1_input_gpu } },
    { binding: 2, resource: { buffer: b2_output_gpu } },
  ],
})

const pipeline = device.createComputePipeline({
  layout: device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout] }),
  compute: { module: device.createShaderModule({ code }), entryPoint: 'main' },
})

// -------------------------- Function to create a new GPUCommandBuffer ---------------------------

const workgroupCount = 1

function createCommandBuffer() {
  const commandEncoder = device.createCommandEncoder()

  commandEncoder.copyBufferToBuffer(b1_input_stage, 0, b1_input_gpu, 0, b1_input_size)

  const passEncoder = commandEncoder.beginComputePass()
  passEncoder.setPipeline(pipeline)
  passEncoder.setBindGroup(0, bindGroup)
  passEncoder.dispatchWorkgroups(workgroupCount)
  passEncoder.endPass()

  commandEncoder.copyBufferToBuffer(b2_output_gpu, 0, b2_output_stage, 0, b2_output_size)

  return commandEncoder.finish()
}

// ------------------------------------------ Executions ------------------------------------------

document.write('<pre>')

let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
document.write(`Loading input = ${input}n`)
await b1_input_stage.mapAsync(GPUMapMode.WRITE)
new Float32Array(b1_input_stage.getMappedRange()).set(input)
b1_input_stage.unmap()

document.write('nExecuting GPUCommandBuffern')
let commands = createCommandBuffer()
device.queue.submit([commands])

await b2_output_stage.mapAsync(GPUMapMode.READ)
let output = new Float32Array(b2_output_stage.getMappedRange()).slice()
b2_output_stage.unmap()
document.write(`Output: ${output}nn`)

input = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
document.write(`Loading input = ${input}n`)
await b1_input_stage.mapAsync(GPUMapMode.WRITE)
new Float32Array(b1_input_stage.getMappedRange()).set(input)
b1_input_stage.unmap()

document.write('nExecuting the same GPUCommandBuffern')
device.queue.submit([commands])

await b2_output_stage.mapAsync(GPUMapMode.READ)
output = new Float32Array(b2_output_stage.getMappedRange()).slice()
b2_output_stage.unmap()
document.write(`Output: ${output} (WRONG?)n`)

document.write('nExecuting a new GPUCommandBuffern')
commands = createCommandBuffer()
device.queue.submit([commands])

await b2_output_stage.mapAsync(GPUMapMode.READ)
output = new Float32Array(b2_output_stage.getMappedRange()).slice()
b2_output_stage.unmap()
document.write(`Output: ${output}nn`)

Here is what I get:

Loading input = 1,2,3,4,5,6,7,8,9,10

Executing GPUCommandBuffer
Output: 10,20,30,40,50,60,70,80,90,100

Loading input = 2,4,6,8,10,12,14,16,18,20

Executing the same GPUCommandBuffer
Output: 10,20,30,40,50,60,70,80,90,100 (WRONG?)

Executing a new GPUCommandBuffer
Output: 20,40,60,80,100,120,140,160,180,200

By the way, the problem is not with read-only-storage. I tried with all 3 buffer types and I get the same results.

How to group result of lookup aggregate results

I aggregate users document:

User.aggregate([
      {
        $match: { _id: req.params.id },
      },
      {
        $lookup: {
          from: 'moods',
          localField: '_id',
          foreignField: 'source.userId',
          pipeline: [
            {
              $lookup: {
                from: 'contactrequests',
                localField: 'source.userId',
                foreignField: 'source.userId',
                let: {
                  // truncate timestamp to start of day
                  moodsDate: {
                    $dateTrunc: {
                      date: '$timestamp',
                      unit: 'day',
                    },
                  },
                },
                pipeline: [
                  {
                    $match: {
                      $expr: {
                        $eq: [
                          '$$moodsDate',
                          {
                            // truncate timestamp to start of day
                            $dateTrunc: {
                              date: '$timestamp',
                              unit: 'day',
                            },
                          },
                        ],
                      },
                    },
                  },
                ],
                as: 'contactRequests',
              },
            },
          ],
          as: 'calendar',
        },
      },
    ]).exec()

There is final document what I get

{
    "_id": "P4SpYVd1KjBaF4SKyVw0E",
    "lastName": "Doe",
    "login": "User-01",
    "name": "John"
    "calendar": [
        {
            "_id": "62a351e33859aaf975c63323",
            "source": {
                "userId": "P4SpYVd1KjBaF4SKyVw0E",
                "deviceId": "Pacjent-141214"
            },
            "timestamp": "2022-06-07T12:44:13.333Z",
            "mood": "good",
            "contactRequests": []
        },
        {
            "_id": "62a351f43859aaf975c63327",
            "source": {
                "userId": "P4SpYVd1KjBaF4SKyVw0E",
                "deviceId": "Pacjent-141214"
            },
           "timestamp": "2022-06-09T12:44:13.333Z",
           "mood": "middle",
           "contactRequests": [
               {
                   "timestamp": "2022-06-09T12:44:13.333Z",
                   "source": {
                       "deviceId": "Pacjent-141214",
                       "userId": "P4SpYVd1KjBaF4SKyVw0E"
                   },
                   "resolve": false,
                   "_id": "62a351ff3859aaf975c63329",
               },
            ]
         }
    ]

},

This is what I would to get. This is more clean and readable.

{
 "_id": "P4SpYVd1KjBaF4SKyVw0E",
  "login": "User-01",
  "name": "John",
  "lastName": "Doe",
  "calendar": [
      {
        "timestamp": "2022-06-11T12:44:13.333Z"  
        "mood": {
            "source": {
              "userId": "P4SpYVd1KjBaF4SKyVw0E",
             },
             "timestamp": "2022-06-11T12:44:13.333Z",
             "mood": "bad",
             "_id": "62a352b83859aaf975c6332d",
         },
         "contactRequest": [
             {
               "timestamp": "2022-06-11T15:25:13.333Z",
               "source" : {
                 "userId":"P4SpYVd1KjBaF4SKyVw0E"
               },
               "resolve": true,
               "_id": "62a351ff3859aaf975c63329"
             },
             {
               "timestamp": "2022-06-11T18:23:13.333Z", 
               "source" : {
                 "userId":"P4SpYVd1KjBaF4SKyVw0E"
               },
               "resolve": false,
               "_id": "62a351ff3859aaf975c63329"
             },
         ]
        }
      }
   ]
}

To achive that I’ve used $group parameter, but at some point I have to declare which field should be fetch to result document and I have problem with contatRequest fields.

{
    $group: {
      _id: {
        $dateToString: {
          format: '%Y-%m-%d',
          date: '$timestamp',
        },
      },
      mood: {
        $push: {
          _id: '$_id',
          source: '$source',
          type: '$mood',
          timestamp: '$timestamp',
        },
      },
      contactRequest: {
        $push: {
          _id: '$contactRequest._id',
          source: '$contactRequest.source',
          resolve: '$contactRequest.resolve',
          timestamp: '$contactRequest.timestamp',
        },
      },
    },
  },
 
  {
    $project: {
      _id: 0,
      timestamp: '$_id',
      mood: 1,
      contactRequest: 1,
    },
  },

Thanks for answer

Autofill extention

AutoFill Extention

Hi,

I was using autofill for a while and as you can see for each filed there is an ID. But now they are changing the ID often, so autorefill is filling fields wrong. Is there any chance to fill fields by description ?

Best
Regards

Interactive bar chart domain issue

I’m trying to create an interactive bar chart of the top Forbes 100 companies, with buttons to change between sales and profit.

The first issue I’m having is with the domain:

x.domain([0, d3.max(data, d => d[xValue])])

Error says “data not defined”

but I defined it here:

d3.csv("data/data_clean.csv").then(data => {
    data.forEach(d => {
    d.sales_usd_billion = Number(d.sales_usd_billion)
    d.profit_usd_billion = Number(d.profit_usd_billion)
})

data snapshot:

rank,company,country,sales_usd_billion,sales_unit,profit_usd_billion,profit_unit,assets_usd_billion,market_usd_billion,sales_usd,profit_usd,assets_usd
1,Berkshire Hathaway,United States,276.09,B,89.8,B,958.78,741.48,276.09,89.8,958.78
2,ICBC,China,208.13,B,54.03,B,5518.51,214.43,208.13,54.03,5518.51
3,Saudi Arabian Oil Company (Saudi Aramco),Saudi Arabia,400.38,B,105.36,B,576.04,2292.08,400.38,105.36,576.04
4,JPMorgan Chase,United States,124.54,B,42.12,B,3954.69,374.45,124.54,42.12,3954.69
5,China Construction Bank,China,202.07,B,46.89,B,4746.95,181.32,202.07,46.89,4746.95
6,Amazon,United States,469.82,B,33.36,B,420.55,1468.4,469.82,33.36,420.55
7,Apple,United States,378.7,B,100.56,B,381.19,2640.32,378.7,100.56,381.19
8,Agricultural Bank of China,China,181.42,B,37.38,B,4561.05,133.38,181.42,37.38,4561.05
9,Bank of America,United States,96.83,B,31,B,3238.22,303.1,96.83,31,3238.22
10,Toyota Motor,Japan,281.75,B,28.15,B,552.46,237.73,281.75,28.15,552.46
11,Alphabet,United States,257.49,B,76.03,B,359.27,1581.72,257.49,76.03,359.27
12,Microsoft,United States,184.9,B,71.19,B,340.39,2054.37,184.9,71.19,340.39
13,Bank of China,China,152.43,B,33.57,B,4192.84,117.83,152.43,33.57,4192.84
14,Samsung Group,South Korea,244.16,B,34.27,B,358.88,367.26,244.16,34.27,358.88

FULL CODE:

//Forbes companies bar chart 

//set up chart area
const MARGIN = { LEFT: 250, RIGHT: 10, TOP: 50, BOTTOM: 100 }
const WIDTH = 1000 - MARGIN.LEFT - MARGIN.RIGHT
const HEIGHT = 1100 - MARGIN.TOP - MARGIN.BOTTOM



const svg = d3.select("#chart-area").append("svg")
    .attr("width", WIDTH + MARGIN.LEFT + MARGIN.RIGHT)
    .attr("height", HEIGHT + MARGIN.TOP + MARGIN.BOTTOM)

const g = svg.append("g")
    .attr("transform", `translate(${MARGIN.LEFT}, ${MARGIN.TOP})`)

// X label
g.append("text")
  .attr("class", "x axis-label")
  .attr("x", WIDTH / 2)
  .attr("y", HEIGHT + 50)
  .attr("font-size", "20px")
  .attr("text-anchor", "middle")

// Y label
const yLabel = g.append("text")
  .attr("class", "y axis-label")
  .attr("x", - (HEIGHT / 2))
  .attr("y", -200)
  .attr("font-size", "20px")
  .attr("text-anchor", "middle")
  .attr("transform", "rotate(-90)")
  .text("Company")

//scales
const x = d3.scaleLinear()
    .range([0, WIDTH])
const y = d3.scaleBand()
    .range([HEIGHT, 0])

//axis generators
const xAxisCall = d3.axisBottom()
const yAxisCall = d3.axisLeft()

//axis groups
const xAxisGroup = g.append("g")
    .attr("class", "x axis")
    .attr("transform", `translate(0, ${HEIGHT})`)
const yAxisGroup = g.append("g")
    .attr("class", "y axis")

//event listeners
$("#var-select").on("change", update)

d3.csv("data/data_clean.csv").then(data => {
    data.forEach(d => {
    d.sales_usd_billion = Number(d.sales_usd_billion)
    d.profit_usd_billion = Number(d.profit_usd_billion)
})


update()
})

function update() {
   
    const t = d3.transition().duration(750)

    //filter based on selections
    const xValue = $("#var-select").val()


    x.domain([0, d3.max(data, d => d[xValue])])
    y.domain(data.map(d => d.company))

   
data.sort(function(a, b) {
    return  b.rank - a.rank;
  })


//update axes
xAxisCall.scale(x)
xAxis.transition(t).call(xAxisCall)
yAxisCall.scale(y)
yAxis.transition(t).call(yAxisCall)

//***Tooltips */


//*** --- */

rects.enter().append("rect")
.attr("y", d => y(d.company) +3)
.attr("x", 0)
.attr("width", d => x(d[value]))
.attr("height", d => 4)