How to implement a like button for posts in a React Social Media Application

So currently, I have an app that takes posts from the NASA Astronomy photo of the day API and uses that for my picture, date, and description data for posts.

enter image description here

I get the json data from this API (stored in variable yeet) and then I pass it to a map function that puts it in a post format. This is where I do that:

enter image description here

And this is the beginning of the soloPost function that takes the data and puts it in the post format I want:

enter image description here

I got my like button component from an npm library called “react-animated-heart,” and it is added to every post (within the soloPost function):

enter image description here

However, I realized that my current implementation of the like button was flawed, as all buttons were updating the same “isClick” state variable, and thus when one like button is clicked for one post, all of the like buttons get updated. However, I cannot declare a state for each post, as I do not know how many posts the API may render at any given time.

Thus, I need a way to add an autonomous like button to each post on my site that doesn’t trigger another button, preferably using state since I am not sure if the npm library I am using would allow for another way.

T-SQL + C# + JavaScript data compatibility (MVC)

I work full stack on many software projects. I create my tables and Stored Procedures on MS SQL Server.

Sometimes a database that I am developing can have more than a hundred tables. And thousands of columns and data structures…

Then I come to the C# side, I prepare datatable vs. on the ado.net side for my stored procedures with Table-Valued Parameters. I redefine the parameters and variables separately in accordance with the tables that I defined in ms sql.

In C#, I create classes again in accordance with the table columns I created on MS SQL.

And finally, I exchange data between C# and JavaScript (between front-end and back-end) with JSON. By applying Serialize to a class in C#…

But before serializing, I create classes (or struct or model, whatever) equivalent to the tables (columns) I created on the JavaScript side, so that I can exchange data between JSON and C# and JavaScript.

Thus, data is exchanged between MS SQL and C# via ADO.NET Table-Valued Parameter, and between C# and JavaScript with JSON.

In short, in order to use the model side of the MVC structure, I have to create C# (class) and JavaScript (class/structure) data models over and over again in accordance with the tables (and columns) I created on the MS SQL side.

Now there are 3 important points about it.

  1. My only solution was to develop an auto-script generator so that I could create a common pattern between T-SQL, C# and JavaScript. Because I developed a software in C# in order not to create the same data model as a table in T-SQL, as a class in C# and as a class/struct in JavaScript. First, I read all my own database, that is, my tables, columns and data structures through ADO.NET, and then I had C# classes and JavaScript classes/structures produced as scripts with the information ADO.NET provided me. This prevented me from wasting my time developing the same data structures separately for T-SQL, for C#, and for JavaScript.

  2. Of course, according to this situation, it required me to write my data structures as T-SQL first and create a database first. So somehow I chose to define data with T-SQL as a starting point.

  3. This was a solution I found myself and I would like to hear how other people are dealing with this situation. Is there any other effective solution for each platform (T-SQL, C# and JavaScript and more) that I haven’t seen? Or did I not see it?

I await your comments. Thanks…

How to customize scrollbar in Material UI?

I am using Material-UI to expand my React project, but i can’t change the scrollbars in the mui components.
This was the css i was using before mui integration:

::-webkit-scrollbar {
    width: 10px;
    height: 10px;
}

::-webkit-scrollbar-track {
    background-color: transparent;
    border-radius: 5px;
    margin: 5px;
}

::-webkit-scrollbar-thumb {
    background-color: #1a1b1c;
    border-radius: 5px;
    border: solid 2px #282c34;
}

::-webkit-scrollbar-thumb:hover {
    background-color: #1a1b1c;
    border-radius: 5px;
    border: solid 2px #1a1b1c;
}

After using mui I realized css is overwritten by mui’s own styling while using mui components such as <Box/> or <Drawer/>. I’m also using <ThemeProvider/> from mui with following theme:

export const dark_theme = createTheme({
  breakpoints: {
    values: {
      mobile: 0,
      desktop: 1024,
    },
  },
  palette: {
    type: "dark",
    primary: {
      main: "#3f51b5",
      contrastText: "#fff",
    },
    secondary: {
      main: "#8700ff",
      contrastText: "#fff",
    },
    background: {
      default: "#282c34",
    },
  },
  typography: {
    fontFamily: "Poppins",
    allVariants: {
      color: "white",
    },
  },
  overrides: {},
});

After trying CSS Baseline overrides from mui documentation, i couldn’t get any results but also couldn’t confirm what was the problem due to my limited understanding of mui`s styling and the fact that CSS Baseline scrollbars was marked deprecated.

how can i integrate the above shown css scrollbar styles to a mui component or mui theme?

Adding one line of code in my project changes the whole program dramatically, please assist me?

So I only have a week’s worth of HTML, CSS, and JavaScript experience, and I’ve been trying to create a game similar to the Dinosaur game on Chrome. I’ve come across a problem trying to store a High Score. For some reason, when I try to update the normal score, the whole game disappears.
Here’s my insulting code:

HTML

<!DOCTYPE html>
<html lang="en" onclick="jump()">
  <head>
    <style>
        #title
        {
            left: 2px;
            position: relative;
        }
        #highscore 
        {
            left: 450px;
            top: 23px;
            position: fixed;
        }
    </style>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Block Game</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <h3 id="title">Block Game</h3>
    <div id="game">
      <div id="score">Score: <br>0</br><div>
      <div id="highscore">Highscore: <br>0</br></div>
      <div id="character"></div>
      <div id="longBlock"></div>
      <div id="block"></div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

CSS

* {
    padding: 0;
    margin: 0;
  }
  #game {
    width: 520px;
    height: 200px;
    left: 2px;
    position: relative;
    border: 1px solid black;
  }
  #character {
    width: 20px;
    height: 50px;
    left: 20px;
    background-color: grey;
    position: relative;
    top: 114px;
  }
  .animate {
    animation: jump 500ms;
  }
  #block {
    width: 20px;
    height: 20px;
    background-color: red;
    position: relative;
    top: 74px;
    left: 500px;
    animation: block 1.5s infinite linear;
  }
  #longBlock {
    width: 40px;
    height: 20px;
    background-color: blue;
    position: relative;
    top: 94px;
    left: 500px;
    animation: block 2s infinite linear;
  }
  @keyframes block {
    0% {
      left: 480px;
    }
    100% {
      left: -40px;
    }
  }
  @keyframes jump {
    0% {
      top: 114px;
    }
    20% {
      top: 67px;
    }
    30% {
      top: 62px;
    }
    70% {
      top: 62px;
    }
    90% {
      top: 109px;
    }
    100% {
      top: 114px;
    }
  }

JavaScript

var score = 0;
var highscore = 0;
var character = document.getElementById("character");
var block = document.getElementById("block");
var longBlock = document.getElementById("longBlock");
document.getElementById("highscore").innerHTML = "High Score: n" + highscore; 
document.getElementById("score").innerHTML = "Score: n" + score;
localStorage.clear();
window.onload = function()
{
    var scoreFromBrowser = localStorage.getItem("highscore");
    if(scoreFromBrowser!= undefined)
    {
    highscore = scoreFromBrowser;
    document.getElementById("highscore").innerHTML = "High Score: " + highscore; 
    }
}

var addScore  = setInterval(function(){
    score+=1;
    document.getElementById("score").innerHTML = "Score: n" + score;
    if(score>highscore) 
    {
        localStorage.setItem("highscore", highscore);
        highscore = score;
        document.getElementById("highscore").innerHTML = "High Score: n" + highscore; 
    }
},200);

function jump(){
    if(character.classList!="animate"){
        character.classList.add("animate");
    }
    setTimeout(function(){
        character.classList.remove("animate");
    },500);
}

var checkDead  = setInterval(function(){
    var characterTop = 
    parseInt(window.getComputedStyle(character).getPropertyValue("top"));
    var blockLeft = 
    parseInt(window.getComputedStyle(block).getPropertyValue("left"));
    var longBlockLeft = 
    parseInt(window.getComputedStyle(longBlock).getPropertyValue("left"));
    if(blockLeft<44 && blockLeft>=5 && characterTop<=130 && characterTop>=84)
    {   
        block.style.animation = "none";
        alert("You Lose. Highscore: " + highscore);
        if(!alert('Replay?'))
        {
            window.location.reload();
        } 
    }
    else if(longBlockLeft<43 && longBlockLeft>=5 && characterTop<=130 && characterTop>=74)
    {   
        block.style.animation = "none";
        alert("You Lose. Highscore: " + highscore);
        if(!alert('Replay?'))
        {
            window.location.reload();
        }
    }
},15);

I wrote this on VSCode and ran it with Live Server. If you delete all the parts like this, document.getElementById("score").innerHTML = "Score: n" + score; The game appears normally. Please Help.

Why won’t file uploads work on the browser despite it working in Postman?

I’m not sure why when making a POST request on Postman, I’m successfully storing the URLs in the DB by grabbing the file and retrieving its name.

But when I try it on the browser, I get a 500 error. The auth token’s coming back correctly, the logged data is also containing the correct information so it’s not entirely clear to me what I’m doing wrong even though I’m doing it exactly the same way as how I’m doing it in Postman and it works fine there.

In the server logs I see an error that says: Call to a member function getClientOriginalName() on null but as mentioned before – the upload works fine on Postman.

What could be issue?

Here’s my JS:

const [selectedFile, setSelectedFile] = useState(null);
let authToken = localStorage.getItem('token');

const onFormSubmit = (e) => {
    e.preventDefault()
    fileUpload(selectedFile);
}

const onChange = (e) => {
    let files = e.target.files || e.dataTransfer.files;
    if (!files.length) {
        return;
    }
    createImage(files[0]);
}

const createImage = (file) => {
    let reader = new FileReader();
    reader.onload = (e) => {
        setSelectedFile(e.target.result);
    };
    reader.readAsDataURL(file);
}

const fileUpload = (selectedFile) => {
    const url = 'http://localhost:8005/api/file-upload';
    const formData = {file: selectedFile}

    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    }

    console.log(authToken);
    console.log(formData);
    console.log(headers);

    JSON.stringify(formData);
    axios.post(url, formData, {
        headers: headers
    }).then(resp => {
            console.log(resp);
        }).catch(error => {
            console.log(error);
        });
}

return (
    <form>
       <input type="file" onChange={onChange} name="userUpload" required/>
       <Button variant="primary" onClick={onFormSubmit}>Upload!</Button>
    </form>
);

“Cannot read properties of undefined” Error when using absolute import in react

I am building a game, and have set up absolute importing in my react app with jsconfig.json like this:

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

and I do have a Config folder with a bunch of config files, and an index.js file that exports them all in a single module, like this:

export { default as PhaserConfig } from "./Phaser.Config"
export * as Objects from "./Objects.Config"
export * as Prefabs from "./Prefabs.Config"
export * as InventoryItems from "./Items.Config"
export {
  initKeyboardInput,
  StarterInventoryItems,
  ColorPallete,
} from "./Game.Config"

so now whenever importing something like this:

import { Objects } from "Config"

console.log(Objects.Sprite) // throws "Cannot read properties of undefined" error

The weird thing is, when launching my react app, there are no errors in the console, it’s just an error message that appears in the react app itself in the browser. Please help!

Mobile site whitening

Hi I have a WordPress site
When I open this site with my mobile, the site page turns completely white for one second. But this problem does not exist in the computer.
I disabled and tested all plugins but it did not work.
What should I do now? If anyone knows please help

add subcategory to category tree in Reactjs

I have a category tree and I want to add a subcategory to it by the “+” button shown inside the subcategory in the picture below.
my problem is I want to add this subcategory to the specific “cloths” category for example, not to all categories, I have an idea of using the category ID I can’t figure out how to do it!

Categories tree

I’ve written this code so far! and I am using JSON-server for fake API calls as follows:

Api Call

import { Formik, Field, Form } from 'formik';
import React, { useEffect } from 'react';
import { getData, postDataDefaultHeader } from '../../Services/Api';
import Modal from '../Modal/Modal';

const ManageCategories = () => {
  const [categories, setCategories] = React.useState(false);
  const [isSubmit, setIsSubmit] = React.useState(false);
  const [addButton, setAddButton] = React.useState(false);

  useEffect(() => {
    getData(`${process.env.REACT_APP_API}/categories`, setCategories);

    if (isSubmit) {
      getData(`${process.env.REACT_APP_API}/categories`, setCategories);
      setIsSubmit(false);
    }
  }, [isSubmit]); //only get categories data when categories is truthy

  return (
    <div>
      <Formik
        initialValues={{
          categoryName: '',
        }}
        onSubmit={(values) =>
          postDataDefaultHeader(
            `${process.env.REACT_APP_API}/categories`,
            values
          )
        }
      >
        {({ values }) => (
          <Form>
            <Field
              name="categoryName"
              type="text"
              placeholder={'add new category'}
            />

            <button onClick={() => setIsSubmit(true)} type="submit">
              save
            </button>
          </Form>
        )}
      </Formik>
      <div>
        {categories &&
          categories.map((category) => (
            <dl key={category.categoryName}>
              <dt>{category.categoryName}</dt>
              {category.subCategory &&
                category.subCategory.map((subCate) => (
                  <dd
                    key={subCate.subCategoryName}
                    value={subCate.subCategoryName}
                  >
                    {subCate.subCategoryName}

                    <div>
                      <button
                        onClick={(id) => {
                          if (id === category.id) {
                            setAddButton(!addButton);
                          }
                        }}
                      >
                        +
                      </button>
                      {addButton && (
                        <div>
                          <input type="text" /> <button>حفظ</button>
                        </div>
                      )}
                    </div>
                  </dd>
                ))}
            </dl>
          ))}
      </div>
    </div>
  );
};

export default ManageCategories;

Typescript way to optimise nested for loop

I have the following nested for loop in my code. this works fine but i am not sure whether this is a good way to do it.i would like to know what is the best optimised way to handle such cases in typescript to get rid of for loops.

for (let j = 0; j <= list.length - 1; j++) {
    const student = list[j];
    for (let i = 0; i <= selectedStudent.subs.length - 1; i++) {
      const id = selectedStudent.subs[i].id;
         if(student[id] === id){
            console.log(id);
          }
    }
  }

How do I combine JavaScript and HTML into a script tag for embedding? [closed]

I’ve been tasked at my internship with adding a range slider with styling into The Gohighlevel platform. I’m very confused on how to write it altogether so they can add it to a section of the site. There is a place in gohighlevel to add custom html/JS but I’m just not sure how to write it. As a disclaimer they’ve had me recreate this slider from react so it can go into the site. I’ve done all of that. I just need an example of how I should write it so they can just embed it on the site and it works. Any help would be appreciated. I find very little documentation about custom code on gohighlevel so it’s getting frustrating. I’ve never done anything like this.

I cannot get toggle state to remember state on refresh, using alpinejs and tailwindcss

I have a toggle using TailwindCSS that when toggled sets a localStorage to true or false. This works, albeit it sets false when on. But my problem is that when the page refreshes the localStorage sticks but the toggle doesn’t and defaults the button to on.

Can anyone explain to me how I can achieve this? It would be greatly appreciated.

Here’s the codepen.

https://codepen.io/williamharvey/pen/xxXaJgM

And here’s the code.

<div 
class="flex w-full items-center bg-gray-100 border-b border-gray-200 px-5 py-3 text-sm"
x-data="{cookieConsent3: localStorage.getItem('Consent3') === 'true'}"
x-init="$watch('cookieConsent3', val => localStorage.setItem('Consent3', val))"
x-bind:class="{ 'Consent3': cookieConsent3 }">
  <div class="flex-1">
    <p>Cookies that measure website use</p>
  </div>
  <div class="w-10 text-right">
    <button type="button" 
      class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-300 bg-gray-200" 
      x-data="{ on: true }" 
      role="switch" 
      aria-checked="false" 
      :aria-checked="on.toString()" 
      @click="on = !on;cookieConsent3 = !cookieConsent3"
      x-state:on="Enabled" 
      x-state:off="Not Enabled" 
      :class="{ 'bg-green-400': on, 'bg-gray-200': !(on) }">
        <span class="sr-only">Use setting</span>
        <span aria-hidden="true" class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200 translate-x-0" x-state:on="Enabled" x-state:off="Not Enabled" :class="{ 'translate-x-5': on, 'translate-x-0': !(on) }"></span>
    </button>
  </div>
</div>

How to prevent checkbox from being checked when a node is clicked on JSTree?

I don’t want the checkbox to be checked when the node is clicked, only when the checkbox itself is clicked.
The code below was copied from the JSTree website I think, and I copied a few lines from a tutorial to enable checkboxes.

        $('#ajaxx').jstree({
      'core' : {
        'data' : {
          "url" : (node)=>{
            return node.id === '#' ?
            './dirfilesapi.php?dirID=-1' :
            ('./dirfilesapi.php?dirID='+node.id);
          },
          "dataType" : "json" // needed only if you do not supply JSON headers
        }
      },"checkbox" : {
                        "keep_selected_style" : false
                    },
                    "plugins": ["checkbox"]
    });

This code runs for grid=12. Can anyone explain why this happens?

Basically the title. I have read every line many times and still can’t find my mistake.
I am just trying to put squares on a grid by calling a recursive function which creates the object and then calls itself again. I have checked that recursion is not infinite and there’s a simple exit condition. Please help.

let grid = 11;
let sqr = [];
function setup() {
  createCanvas(grid * grid, grid * grid);
  noFill();
  colorMode(HSB);
  noLoop();
  let maxs = floor(grid / 3);
  let ratio = 2 * maxs * maxs;
  makegrid(maxs, ratio);
}
function draw() {
  background(0);
  for (let sq of sqr) sq.show();
}
function makegrid(m, r) {
  if (!m) return;
  if (m == floor(grid / 3)) {
    for (let i = 0; i < 2; i++) sqr.push(new sqrs(m, r));
    m--;
    makegrid(m, r);
  } else {
    let j = r / (m * m);
    for (let k = 0; k < j; k++) sqr.push(new sqrs(m, r));
    m--;
    makegrid(m, r);
  }
}

class sqrs {
  constructor(m, r) {
    let flag = true;
    this.s = (m * width) / grid;
    while (flag) {
      flag = false;
      this.x = (width / grid) * floor((grid + 1 - m) * random());
      this.y = (height / grid) * floor((grid + 1 - m) * random());
      if (!sqr.length) flag = false;
      else {
        for (let sq of sqr) {
          let d = (this.x - sq.x) ** 2 + (this.y - sq.y) ** 2;
          if (d < this.s ** 2 || d < sq.s ** 2) {
            flag = true;
            break;
          }
        }
      }
    }
  }

  show() {
    stroke(random(340), 80, 80);
    square(this.x, this.y, this.s);
  }
}