Problem with React Context State not Updating in real time. It only updates when i reload but not immediately

I am facing an issue in my React application where the state within a React context is not updating immediately, but only after I reload the page. I think maybe it’s wrong in the UPDATE case in WorkoutsContext.jsx

WorkoutsContext.jsx

const workoutsReducer = (state, action) => {
  switch (
    action.type 
  ) {
..
    case "UPDATE_WORKOUT":
      return {
        workouts: state.workouts.map((w) => (w._id === action.payload._id ? action.payload : w)),
      };
..
  }
};

const WorkoutContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(workoutsReducer, {
    workouts: null,
  });

  return <WorkoutsContext.Provider value={{ ...state, dispatch }}>{children}</WorkoutsContext.Provider>;
};

UpdateModal.jsx

const UpdateModal = ({ closeModal, initialValues }) => {
..
  const { dispatch } = useWorkoutsContext();

  const handleSubmit = async (e) => {
    e.preventDefault();
..
    const response = await fetch("api/workouts/" + initialValues.id, {
      method: "PATCH",
      body: JSON.stringify(updatedWorkout),
      headers: {
        "Content-Type": "application/json",
      },
    });
    const json = await response.json();
..
    if (response.ok) {
      console.log("workout updated");
      dispatch({ type: "UPDATE_WORKOUT", payload: json });
    }
  };

Twitch Websocket disconnects immediately

I’m trying to make a programm to display any message that is written in a Twitch chat, with the Twitch websocket, like Chatterino, Chatsen, etc.

I’m using this package: https://www.npmjs.com/package/ws

I’m very new to websockets and never worked with them before. I was able to connect with the websocket, but it disconnects immediately after connecting, with the Close Code: Code: 1006. I don’t understand what this code means and an solution for the error.

const WebSocket = require('ws');
const twitchUrl = 'wss://irc-ws.chat.twitch.tv/';
const twitchChannel = ''; // my twitch username
const twitchToken = 'auth: [REDACTED]'
const ws = new WebSocket(twitchUrl);

ws.on('open', () => {
  console.log('Connected to Twitch Chat');
  ws.send(`JOIN ${twitchChannel}`);
  ws.send(`PASS ${twitchToken}`);
  ws.send(`NICK ${twitchChannel}`);
});

ws.on('message', (data) => {
  let message = data.toString()
  console.log(`Message: ${message}`);
});

ws.on('error', (error, code, reason) => {
  console.log(`Error: ${error} Code: ${code}. Reason: ${reason}`);
});

ws.on('close', (code, reason) => {
  console.log(`Connection closed! Code: ${code}. Reason: ${reason}`);
});

Game loading animation freezes

My problem is that when I start the game the animation freezes, the game is written in Javahow can this problem be solved? And what could this be connected with? Please help me, I will be grateful, here is a link to a short video: https://imgur.com/a/fuHcPnr

Myself Nothing I didn’t take any steps to avoid making a mistake, I’ll wait for an answer, thank you for your attention!

Youtube fullscreen button not working using Youtube API

I am using Youtube API for loading youtube videos in webview for Android. Everything is working fine but the click event for full screen is not triggered.

Below is my code:

private fun getHTMLData(videoId: String): String {
        return """
        <!DOCTYPE html>
        <html>
            <body style="margin:0px;padding:0px;">
                <div id="player"></div>
                
                <script src="https://www.youtube.com/iframe_api"></script>
                <script>
                    var player;
                    function onYouTubeIframeAPIReady() {
                    
                       console.error("-------playing-------");
                        player = new YT.Player('player', {
                       
                            width: '100%',
                            videoId: '$videoId',
                            playerVars: {
                                'playsinline': 1,
                                'allowfullscreen': 1 // Enable fullscreen mode
                            },
                            events: {
                                'onReady': onPlayerReady,
                                'onStateChange': onPlayerStateChange
                            }
                        });
                        
                        // Call updateHeight function on initial load
                        updateHeight();
                       
                    }
                    
                    function onPlayerReady(event) {
                       console.error("-------onPlayerReady-------");
                        event.target.playVideo();
                        
                        // Attach click event listener to the full-screen button
                     var fullScreenButton = document.querySelector(".ytp-fullscreen-button");
                     if(fullScreenButton){
                     fullScreenButton.addEventListener('click', function() {
                       toggleFullScreen();
                     });
                     }else{
                      console.error("-------Fullscreen button not found-------");
                     }
                     
                    }


                    function onPlayerStateChange(event) {
                        // Handle player state changes here if needed
                       
                    }

                    function toggleFullScreen() {
                    
                        console.error("Toggling fullscreen");
                        if (player.isFullscreen()) {
                            player.exitFullscreen();
                        } else {
                            player.playVideo(); // Autoplay is required for full-screen on mobile devices
                            player.getIframe().requestFullscreen();
                        }
                    }
                    
                  
                    function updateHeight() {
                        var screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
                        document.getElementById('player').style.height = (screenHeight) + 'px';
                    }
                </script>
               
            </body>
        </html>
    """.trimIndent()
    }

I am loading this in webview as :

 webView.apply {
            settings.javaScriptEnabled = true
            settings.loadWithOverviewMode = true
        }

        webView.webChromeClient = object : WebChromeClient() {
            override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
                Log.e("WebView------------->>>", consoleMessage.message())
                return true
            }
        }

        val htmlData =
            getHTMLData(id)
        webView.loadData(htmlData, "text/html", "utf-8");

I am getting error log that is inside the else block console.error("-------Fullscreen button not found-------");

Am i missing something?

Make every element different (no repeat) color from randomly generated list of colors

I have an array of colors and then I randomized them. I want to assign different color to each list item instead of having items with the same colors or having repeated colors.

const myList = document.querySelector('.myList');
const listItems = myList.querySelectorAll('li');
const itemColors = ['red', 'green', 'royalblue', 'purple','cornflowerblue', 'sienna','palevioletred','orange'];

listItems.forEach((item, index) => {
  

  let randomColors = itemColors[Math.floor(Math.random() * itemColors.length)];
   item.style.color = randomColors;
  
});
<ul class="myList">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
  <li>Soup</li>
  <li>Juice</li>
  <li>Beer</li>
  <li>Wine</li>
  <li>Soda</li>
</ul>

for loop not running in javascript

i have a problem with my svelte code. on the line 41 i have a for loop, which doesn’t run anything, as it doesn’t print out the i variable on the 42 line.

here is my code:

<script>
    import Toolbar from "./toolbar.svelte";
    import Chat from "./chat.svelte";
    var loggedInUser = "dev"
    //database
    var users =
    {
        "dev":{
            "contacts":["Voldemart", "Timur", "Svyat"],
        }
    }

    var chats = {
        0:{"name":"None","members":["Voldemart", "dev"], "messages":[
            {"content":"hi", "sender":"dev"},
            {"content":"pon", "sender":"Voldemart"},
        ]},

        1:{"name":"None","members":["Timur", "dev"], "messages":[
            {"content":"hi", "sender":"dev"},
            {"content":"pon", "sender":"Timur"},
        ]},

        2:{"name":"None","members":["Svyat", "dev"], "messages":[
            {"content":"hi", "sender":"dev"},
            {"content":"pon", "sender":"Svyat"},
        ]},

        3:{"name":"None","members":["Voldemart", "Svyat"], "messages":[
            {"content":"hi", "sender":"Svyat"},
            {"content":"pon", "sender":"Voldemart"},
        ]},
    }

    console.log(chats[0].members.includes(loggedInUser))

    var loggedInUserChats = []
    var i;
    var chatsLength = Object.keys(chats).length
    console.log(chatsLength)
    for (i; i<5; i++) {
        console.log(i)
        if (chats[0].members.includes(loggedInUser)) {
            loggedInUserChats.push(i)
            console.log(i)
        }
    }
    console.log(loggedInUserChats)
</script>
<Toolbar contacts="{users[loggedInUser].contacts}"/>
<div class="chaty">
    <Chat/>
</div>

<style>
    .chaty {
        width: 100%;
        height: 100vh;
        margin-left: 200px;
    }
</style>

i have tried asking gemini, i have tried reading mdn docs and w3schools docs but i found nothing.

Apollo Server v4 throws Cors issue

I am getting the typical CORS issue while accessing my backend

Here is my backend code

const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});

await server.start();

app.use(
  "/graphql",
  cors({
    origin: "http://localhost:3000/",
    credentials: true,
  }),
  express.json(),
  expressMiddleware(server)
);

await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));

console.log("Server started at ", 4000);

Here is my frontend code

First way:

const client = new ApolloClient({
    cache: new InMemoryCache(),
  
    link: new HttpLink({
      uri: "https:/localhost:4000/graphql",
      
    }),
  });

Second way

const client = new ApolloClient({
    uri: "https:/localhost:4000/graphql",
    cache: new InMemoryCache(),
  });

Tried both way but still the issue persists

Strapi won’t restart // Force Node version?

Two times I totally reinstalled Strapi in my prod because SQLite 3 crashed & the app with it.

I created a Next App, I want to connect my API to it. So I have two apps (in two folders) in my working folder :

  • webfolio (Next.js)
  • webfolio-api (Strapi)

The thing is, in my first session, everything runs well. When I come back later & restart the two servers, the Strapi one crashes.

~/OneDrive/Documents/code/fullstack/webfolio-api ((0e19669...)) > npm run develop

> [email protected] develop
> strapi develop

⠋ Building build context
[INFO] Including the following ENV variables as part of the JS bundle:
    - ADMIN_PATH
    - STRAPI_ADMIN_BACKEND_URL
    - STRAPI_TELEMETRY_DISABLED
✔ Building build context (129ms)
✔ Creating admin (13012ms)
⠸ Loading StrapiC:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbindingsbindings.js:126
  err = new Error(
        ^

Error: Could not locate the bindings file. Tried:
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3buildbetter_sqlite3.node
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3buildDebugbetter_sqlite3.node    
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3buildReleasebetter_sqlite3.node  
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3outDebugbetter_sqlite3.node      
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3Debugbetter_sqlite3.node
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3outReleasebetter_sqlite3.node    
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3Releasebetter_sqlite3.node        
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3builddefaultbetter_sqlite3.node  
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3compiled20.11.0win32x64better_sqlite3.node
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3addon-buildreleaseinstall-rootbetter_sqlite3.node
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3addon-builddebuginstall-rootbetter_sqlite3.node
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3addon-builddefaultinstall-rootbetter_sqlite3.node
 → C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3libbindingnode-v115-win32-x64better_sqlite3.node
    at bindings (C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbindingsbindings.js:126:9)
    at new Database (C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesbetter-sqlite3libdatabase.js:48:64)
    at Client_BetterSQLite3.acquireRawConnection (C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesknexlibdialectsbetter-sqlite3index.js:14:12)
    at create (C:UserssamueOneDriveDocumentscodefullstackwebfolio-apinode_modulesknexlibclient.js:262:39) {
  tries: [
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\build\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\build\Debug\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\build\Release\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\out\Debug\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\Debug\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\out\Release\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\Release\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\build\default\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\compiled\20.11.0\win32\x64\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\addon-build\release\install-root\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\addon-build\debug\install-root\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\addon-build\default\install-root\better_sqlite3.node',
    'C:\Users\samue\OneDrive\Documents\code\fullstack\webfolio-api\node_modules\better-sqlite3\lib\binding\node-v115-win32-x64\better_sqlite3.node'
  ]
}

My main expectation is I accidentally started Strapi with Node 21 as it needs to start with node <= 20.x.x

Do you know how to restore the database? Even a git checkout can’t allow me to restart the Strapi app with the right node version. Do you know how to force my Strapi app to start with node 18.x.x to secure it? Or do you have an idea to better organize that two apps?

Thanks for all!

For some reason this is not doing anything, I think it may be the button

I am trying to make a webpage that when you put a number in the box, and press a button, it tells you if the number is even or odd in the console, but when I press submit, it doesn’t do anything.

This is my code, is there anything I should change or fix?
I thought it would tell me if it was even or odd but it didn’t do that.

const num = document.getElementById("numberText");
const result = document.getElementById("result");
const button = document.getElementById("submitBtn");

function isEven(number){
    if (number % 2 === 0) {
        return "this number is even";
    } else {
        return "this number is odd";
    }
}

if (button.clicked == true) {
    console.log(isEven(num));
}

How do play local video file in Electron

I try do learn Electron and want play local video file. I have follow all examples I find but all are dates from 5 more years and not work. Why no work example of regular job?

Sorry for English bad.

I try to use <input type="file" id="video-input" /> and get good path to file: files[0].path but when use in <source kind="video/mp4" src={video} /> nothing work.

I try to add:

protocol.handle('media-loader', (request) => {
  return net.fetch(`media-loader://${request.url.slice('media-loader://'.length)}`);
});

I find https://github.com/amilajack/erb-video-example and add changes from https://github.com/amilajack/erb-video-example/commit/0706e53795dc11b4d8a0932b3a9d6de572de6c71#diff-d9d75cc1dda9c5e912390983ac6b263a

Nothing works. Cannot find example not over 5 years old.

css transition for var inside “background: linear-gradient” not working in firefox but working in chrome

I wanted a smooth transition of “background: linear-gradient” color when scrolling(with transition and var).
It works fine in Chrome, but in Firefox the transition is instantaneous.

I have no idea what im doing wrong

My test code. On scroll(js script) change class for div from “item-static” to “item-sticky”.

Html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style/style_test.css">
    <script defer src="js/test.js"></script>
    <title>Document</title>
</head>

<body>
    <div class="target static-item"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente alias quod ullam.</div>

    <div class="big-box" style="height: 120vh; background: black;"></div>
</body>

</html>

Css

@property --myColor1 {
    syntax: '<color>';
    initial-value: rgba(85, 85, 249, 1);
    inherits: false;
}

@property --myColor2 {
    syntax: '<color>';
    initial-value: rgb(255, 255, 255);
    inherits: false;
}

.target{
    top:0;
}

.flex-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    top: 0;
    z-index: 3;
    background: white;
}

.sticky-item {
    position: sticky;
    --myColor1: rgb(255, 255, 255);
    --myColor2: rgb(255, 255, 255);
    transition: --myColor1 1s ease-in-out, --myColor2 1s ease-in-out;
    background: linear-gradient(180deg, var(--myColor1) 0%, var(--myColor2) 100%);
}

.static-item {
    position: static;
    --myColor1: rgba(85, 85, 249, 1);
    --myColor2: rgb(255, 255, 255);
    transition: --myColor1 1s ease-in-out, --myColor2 1s ease-in-out;
    background: linear-gradient(180deg, var(--myColor1) 0%, var(--myColor2) 100%);
}

Unable to deploy Backend of my full stack website to Vercel, getting internal server error

Getting this Error while deploying:

This Serverless Function has crashed.

Your connection is working correctly.

Vercel is working correctly.

500: INTERNAL_SERVER_ERROR
Code: FUNCTION_INVOCATION_FAILED

This is my vercel.json file, has vercel updated this json file format or syntax?

{
  "version": 2,
  "builds": [
    {
      "src": "*.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/"
    }
  ]
}

This is the error in my deployment logs in GET request of /favicon.ico:

Invoke Error    {"errorType":"TypeError","errorMessage":"Right-hand side of 'instanceof' is not an object","stack":["TypeError: Right-hand side of 'instanceof' is not an object","    at Ee (/opt/node-bridge/bridge-server-D2QTJ22O.js:1:3211)","    at Ie.e.request (/opt/node-bridge/bridge-server-D2QTJ22O.js:1:3791)","    at it.handleEvent (/opt/node-bridge/vercel-tla.js:10:111)","    at async Runtime.launcher [as handler] (/opt/node-bridge/vercel-tla.js:9:645)"]}

Changed vercel.json multiple times.

Restricting Memory Game to Only Allow Two Cards Open at Once in React

I’m creating a simple memory game in react and have a problem where it is possible to select more than two cards at once. The game works as it should when only clicking two cards, but breaks if you select more.

I have tried to limit the amount of cards in openCards to 2 before flipping another, but it didn’t work. I have also considered adding all cards that are not open to disabledCards when you’ve selected two, but that would mix them up with the cards that are already a match.

function App() {
  const [images, setImages] = useState([]);
  const [openCards, setOpenCards] = useState([]);
  const [shouldFlipBack, setShouldFlipBack] = useState(false);
  const [disabledCards, setDisabledCards] = useState([]);  //cards that are matched
  const imageArray = [
    {type: "penguin", image: penguin},
    {type: "penguin", image: penguin},
    {type: "snail", image: snail},
    {type: "snail", image: snail},
    {type: "chicken", image: chicken},
    {type: "chicken", image: chicken},
    {type: "raccoon", image: raccoon},
    {type: "raccoon", image: raccoon},
    {type: "fox", image: fox},
    {type: "fox", image: fox}
  ];

  useEffect(() => {
    setImages((prevImages) => shuffleImages(prevImages));
  }, []);
  
  useEffect(() => {
    if (openCards.length === 2) {
      checkIfMatch();
      setOpenCards([]);
    }
  }, [openCards]);

  function checkIfMatch() {  
    if (openCards[0] === openCards[1]) {
      console.log("match");
      setDisabledCards(()=> [...disabledCards, openCards[0]]);
      setShouldFlipBack(false);

    } else {
        console.log("not match");
        setTimeout(() => {
          setShouldFlipBack(true);
        }, 1000); 
    }
    setShouldFlipBack(false);
  }
function Card({card, setOpenCards, openCards, shouldFlipBack, disabledCards}) {
  const [isFlipped, setFlipped] = useState(false);

  useEffect(() => {
    if (!disabledCards.includes(card.type)) {
      setTimeout(() => {
        setFlipped(false);
      }, 500);
    }
  }, [shouldFlipBack]);

  function flipCard() {
    if (!disabledCards.includes(card.type)) {
      setFlipped(!isFlipped);
      setOpenCards(()=> [...openCards, card.type]);
    }
  }
  return (
    <div className="card" onClick={flipCard}>
      <div className={isFlipped ? "card-inner flipped" : "card-inner"}>
        <div className="card-front"></div>
        <div className="card-back">
          {isFlipped && <img src={card.image} alt="card" />}
        </div>
      </div>
    </div>
  );
}

export default Card;

CRM 365 on-prem: Use JavaScript to pass variables between different forms in the same entity

enter image description here

Process: User clicks a button from the parent entity “A”, and it passes the GUID and name of the current record to a new record in entity “B”.

The new record loads and triggers an OnLoad event. It retrieves the parameters that were passed from the parent. This works perfectly.

Now, I have requirement to have 2 versions of the form on entity “B”. The moment I switch from “Account Info” (that has all the populated values), “Account Info (ADMIN) 1.0” loads and nothing populates. If I refresh the browser, “Account Info (ADMIN) 1.0” loads and the data populates.

How do I retain the parameters, when switching between forms in the same entity?

I haven’t found a way to store the initial parameters, without saving the record. is this even possible?

Not getting specific product details on click it get only first product details on popup. How to get specific product details on action button click

I am using angular 15. Displaying products in a page where every product have a action button after click on it a popup(bootstrap model) appears which has form in form product details appear and update and delete buttons is there but when I click on action it will only geting first product details for every product.How can I get specific product details on action button click. I am using json server

Product component

{{items.product}}
Price  {{items.price}}

<button type=”button” class=”btn btn-primary” data-bs-toggle=”modal”

data-bs-target=”#exampleModal”

Action

<1– Modal –>

aria-labelledby=”exampleModalLabel”

aria-hidden=”true”>

Modal titleh1>

<button type=”button” class=”btn-close” data-bs-dismiss=”modal”

| aria-label=”Close”>

Name of the Product

input type=”text” class=”form-control” name=”product”

| value=”{{items.id}}”>

Price of the Product

<input type=”text” class=”form-control” name=”price” value=”

{{items.price}}”>

<button type=”button” class=”btn btn-secondary”

data-bs-dismiss=”modal”>Close

<button class=”btn btn-danger” (click)=”deleteProduct(items.id)” data-bs-dismiss=”modal”>Delete

<button type=”button” class=”btn btn-primary”

data-bs-dismiss=”modal”>Update

Ts file

export class ProductHomeComponent implements OnInit {

productList: any

constructor(private product: ProductService, private router: Router) { }

ngOnInit(): void { I

this.product.getProduct().subscribe((res) => {

if (res) {

this.productList = res

} else {

console.log(“product”, res);

}

})

}

}

else {

deleteProduct(id: any) {

console.log(“id”,id)

this.product.deleteProduct(id).subscribe((res) => {

if (res) {

console.log(“deleted successfully”)

window.location.reload();

console.log(“not delete, check again”)

}

})

Service file

export class ProductService {

url=’http://localhost:3000/products’

constructor(private http: HttpClient) {}

addProduct(data: any) {

return this.http.post(this.url, data)

}

getProduct() {

return this.http.get(this.url)

deleteProduct(id: any) {

return this.http.delete(“http://localhost:3000/products/${id}”)

}

}