I am getting this error SyntaxError: Invalid Unicode escape sequence at eval () error adding console log in the getStaticProps()

This is my page users.js

import React from 'react'

const users = ({users}) => {
  return (
    <>    {
      users.map(user => {
        return <div key={user.id}> {user.name} </div>
      })
    }
    </>
  )
}



export default users


export async function getStaticProps() {
    const res = await fetch('https://jsonplaceholder.typicode.com/users')
    const users = await res.json()

    console.log("users", users)  

    return {
      props: {
        users,
      },
      // Next.js will attempt to re-generate the page:
      // - When a request comes in
      // - At most once every 10 seconds
      revalidate: 10, // In seconds
    }
  }

When I Run This I get this below error in my terminal, instead how can I see the users value in my terminal?

`error - SyntaxError: Invalid Unicode escape sequence
    at eval (<anonymous>)
    at oo_oo (webpack-internal:///./pages/users.js:50:14)
    at users (webpack-internal:///./pages/users.js:14:5)
    at renderWithHooks (C:UsersudaysDocumentsNEXTLEARNnext-pre-rendernode_modulesreact-domcjsreact-dom-server.browser.development.js:5658:16)


`

I have tried to comment out

`   reactStrictMode: true,`

but it did not work.

Your Help is much appreciated!!

In Knockout how do you go about nesting custom components when using an html binding?

I’m a bit new to knockout. I’m trying to get a custom component to dynamically load another custom component. I have a variable called location_board that contains html and that html has a custom component in it. . When I use the data-bind=”html: location_board” it put the line for the in the dom but it doesn’t run the custom component to fill out that node. Note: If I add the npc-widget directly to the template it works. It just doesn’t work when it is added though the html binding. From my research I think this means I need to applyBindings on it? I’m not sure how to go about that in this situation though.

Any help is apricated.

Here is my full code for the custom component.

import {Database} from './database.js'
let database = new Database();
import {ResourceManager} from "./resource-manager.js";
let resourceManager = new ResourceManager();
let locationRegister = {
    fog_forest: {
        name: "The Ghostly Woodland",
        image: "url('img/foggy_forest.jpeg')",
        description: `
Place holder
        `,
        location_board: `
<npc-widget id="john-npc" params="id: 1, tree: 'shopkeep', speed: 50"></npc-widget>
<div>In</div>
`
    }
};

ko.components.register('location-widget', {
    viewModel: function (params) {
        let self = this;
        self.function = function () {
            console.log("Functions!")
        }

        for(let k in locationRegister[params.id]) {
            console.log(k)
            this[k] = locationRegister[params.id][k];
        }
        console.log(this.name)
        //return { controlsDescendantBindings: true };
    },
    template:
        `
<div class="row">
        <div class="col-lg-12">
            <h2 id="title" class="tm-welcome-text" data-bind="html: name"></h2>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-12">
            <div data-bind="style: { 'background-image': image}" class="location-picture mx-auto d-block">
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-12">
            <div class="location-description mx-auto d-block" data-bind="html: description"></div>
        </div>
    </div>
</div>
<hr>
<div class="row">
    <div class="col-lg-12">
        <div id="location_board" data-bind="html: location_board">
            
        </div>
    </div>
</div>
`
});

Why useState updates immediately inside the html of component but inside functions of component only update on next render? [duplicate]

useState updates immediately inside html codes but in functions will only update on next render?

import { useState } from ‘react’

function weird() {

const [data, setData] = useState('previous')

function submit(e) {    <---- when I fired the submit event Form once
    setData('updated')   
    console.log(data)   <---- this will log "previous" value
}
return (
    <from onSubmit={(e)=> submit(e)}>
        {data ? console.log(data) : ''}   <---- but this will log "updated" value
    </from>
)

}
export default weird

Calculator wont ignore periods being added to decimals

I’m trying to finish off this calculator and it wont let me do what the title says.

export default function App() {
  const [activeKey, setActiveKey] = useState(0);
  const [storeArr, setStoreArr] = useState([]);

  function click(selector) {
    //set active key
    setActiveKey(selector);

    /*
    clear if store is empty
    set same state is store is one number
    calculate equation
    */
    if (activeKey === "=") {
      if (storeArr.length === 0) {
        return clear();
      } else if (storeArr.length === 1) {
        setStoreArr(storeArr);
      } else if (storeArr.length > 1) {
        calculate([...storeArr]);
      }
    } else {
      // dont let 2 zeros start a number
      if (
        typeof selector === "number" &&
        storeArr.length > 0 &&
        typeof storeArr[storeArr.length - 1] === "number" &&
        storeArr[storeArr.length - 1] === 0
      ) {
        return;
      }

      //dont let 2 symbols be added to storeArr
      else if (
        typeof selector !== "number" &&
        storeArr.length > 0 &&
        typeof storeArr[storeArr.length - 1] !== "number"
      ) {
        storeArr[storeArr.length - 1] = selector;
        return;
      }

      //dont let 2 periods be in a number
      else if (
        selector === "." &&
        storeArr.length > 0 &&
        !Number.isInteger(storeArr[storeArr.length - 1])
      ) {
        return;
      }

      // add number to storeArr
      else {
        setStoreArr([...storeArr, selector]);
      }
    }
  }

  // clear function, cmon man
  function clear() {
    setStoreArr([]);
    setActiveKey(0);
  }

  //calculate function
  function calculate(arr) {
    // combine consecutive numbers into a single number
    for (let i = 0; i < arr.length; i++) {
      if (typeof arr[i] === "number" && typeof arr[i + 1] === "number") {
        arr[i] = arr[i] * 10 + arr[i + 1];
        arr.splice(i + 1, 1);
        i--;
      }
    }

    // perform multiplication and division first
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === "x") {
        arr[i - 1] = arr[i - 1] * arr[i + 1];
        arr.splice(i, 2);
        i--;
      } else if (arr[i] === "/") {
        arr[i - 1] = arr[i - 1] / arr[i + 1];
        arr.splice(i, 2);
        i--;
      }
    }

    // perform addition and subtraction
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === "+") {
        arr[i - 1] = arr[i - 1] + arr[i + 1];
        arr.splice(i, 2);
        i--;
      } else if (arr[i] === "-") {
        arr[i - 1] = arr[i - 1] - arr[i + 1];
        arr.splice(i, 2);
        i--;
      }
    }

    // return the result
    setStoreArr(arr[0]);
  }

  const topFuncs = [
    {
      name: "clear",
      text: "AC"
    },
    {
      name: "divide",
      text: "/"
    }
  ];

  const numsDiv = [
    {
      name: "seven",
      text: 7
    },
    {
      name: "eight",
      text: 8
    },
    {
      name: "nine",
      text: 9
    },
    {
      name: "four",
      text: 4
    },
    {
      name: "five",
      text: 5
    },
    {
      name: "six",
      text: 6
    },
    {
      name: "one",
      text: 1
    },
    {
      name: "two",
      text: 2
    },
    {
      name: "three",
      text: 3
    },
    {
      name: "zero",
      text: 0
    },
    {
      name: "decimal",
      text: "."
    }
  ];

  const rightDiv = [
    {
      name: "multiply",
      text: "x"
    },
    {
      name: "subtract",
      text: "-"
    },
    {
      name: "add",
      text: "+"
    },
    {
      name: "equals",
      text: "="
    }
  ];

  return (
    <div className="App">
      <div id="outer-div" className="outer-div">
        <div className="store-display">{storeArr}</div>
        <div id="display" className="display">
          {activeKey}
        </div>

        <div className="left-right">
          <div id="left-div" className="left-div">
            <div className="top-funcs">
              {topFuncs.map((i) => (
                <button
                  id={i.name}
                  className="btn"
                  key={i.text}
                  onClick={() => {
                    if (i.text === "AC") {
                      return clear();
                    } else {
                      click(i.text);
                    }
                  }}
                >
                  {i.text}
                </button>
              ))}
            </div>
            <div id="nums-div">
              {numsDiv.map((i) => (
                <button
                  id={i.name}
                  className="btn"
                  key={i.text}
                  onClick={() => {
                    click(i.text);
                  }}
                >
                  {i.text}
                </button>
              ))}
            </div>
          </div>
          <div id="right-div" className="right-div">
            {rightDiv.map((i) => (
              <button
                id={i.name}
                className="btn"
                key={i.text}
                onClick={() => {
                  if (i.text === "=") {
                    calculate([...storeArr]);
                  } else {
                    click(i.text);
                  }
                }}
              >
                {i.text}
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Ive tried to write the click function to include a loop that checks if the last element in the storeArr display is a decimal, and returns without doing anything if the activeKey state is a period, I’ve tried regex and the includes method aswell

Content Security Policy inline scripts has been blocked html form js php

I am having trouble implementing CSP with nonce and I’m not understanding what I am doing wrong. I am able to execute local scripts which I’m assuming is allowed the the ‘self’ parameter. However when I try to submit a contact form which onsubmit execute a return on a js function that sends a post request to a php file to send a email it apparently qualifies as an inline script execution and get blocked by CSP. I have tried to implement nonce in various ways but I’m just not understanding how to enable its execution without using ‘unsafe-inline’. Any help would be appreciated. I’m using the following code:

I am specifically getting an error for inline executing from the ‘script-src’ policy

.htaccess

Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'strict-dynamic' 'nonce-12345678' https://example.com; style-src 'self' 'unsafe-inline'; base-uri 'self'; script-src-elem 'self'; img-src 'self' data:; form-action 'self'; report-to csp-endpoints"

contact.html

<form id="contact_form" onsubmit="return submitForm()" class="form_grid" nonce="12345678>
<script src="/js/contact.js" nonce="12345678"></script>

contact.js

function submitForm(e) { 
    
    // do stuff
    
    const request = new XMLHttpRequest();
    request.open("POST", "php/email.php", true);
    request.setRequestHeader("Content-type", "application/json");
    request.onload = function () {
        if (request.status >= 200 && request.status < 400) {
            const resp = request.responseText;
            const data = JSON.parse(resp);
            alert(`Thank you ${data.name} for your message. We will get back to you at ${data.email} as soon as possible.`);
        } else {
            alert("Something went wrong. Please try again later.");
            console.log(request.responseText);
        }
    };
    request.onerror = function () {
        alert("An error occured. Please try again later.");
    };

    const data = JSON.stringify({
        name,
        email,
        goal,
        itsatrap,
        requirements,
        integrations,
        features,
        guidelines
    });
    request.send(data);
    return false;
  }
}

email.php

<?php
   // do stuff
   header('Content-Type: application/json');
   if (mail($recipient, $subject, $email_content, $email_headers)) {
     http_response_code(200);
     $json = array("success" => true, "message" => "Thank You! Your message has been sent.", "name" => $name, "email" => $email);
     echo json_encode($json, JSON_PRETTY_PRINT);
     exit;
   } else {
     http_response_code(500);
     $json = array("success" => false, "message" => "Oops! Something went wrong and we couldn't send your message.", "reason" => error_get_last());
     echo json_encode($json, JSON_PRETTY_PRINT);
     exit;
   }

How can I overlay text on image in ReactJS/NextJS application?

I am having some trouble getting the css styles to apply as intended. I’m writing this application in ReactJS/NextJS. I am trying to create a component that shows an image with text positioned on top of image. I expect the CSS styles that I’m applying to work, because I’ve already tested the styles through w3schools. I’m attaching screenshot of what I’ve done in w3schools, what I’m currently doing in my code, and how everything looks in my localhost:3000. The div with imageContainer1, has a background-image applied to it in the css file, but the image is not appearing on screen. The image that does appear is from the second div with inline styling (which I copied from somewhere, can’t remember). The thing is that when I remove the inline styles and move the styles inside the style tags or in the css file, the styles no longer want to apply as they did inline. It’s quite confusing how the styling is inconsistent when I move it.

Alas, the goal is to show an image, at full width of the viewport, with text positioned on top of the image. I appreciate any pointers.

enter image description here

enter image description here

enter image description here

Getting a JSON circular structure error when updating a model’s field

I am building an e-commerce web application with NodeJS with express and MongoDB. I working on an API for storing a product id and quantity in an array that is the user’s cart.

This is the user model:

const userSchema = mongoose.Schema({
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true
    },
    access_level: {
        type: Number,
        default: 1
    },
    cart: {
        type: [cartProductSchema],
        default: []
    }
})

This is the model for cartProductSchema:

const cartProductSchema = new mongoose.Schema({
    product_id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Product'
    },
    quantity: {
        type: Number,
        required: true,
        validate: { validator: Number.isInteger }
    }
}, { _id: false })

This is the model for the Product:

const productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    description: {
        type: String,
        required: true,
    },
    price: {
        type: Number,
        required: true,
    },
    stock: {
        type: Number,
        required: true,
        validate: { validator: Number.isInteger }
    }
}, {timestamps: true})

Here is the snippet of the router where the error is.:

// Add product to user's cart
const product = await Product.findOne({_id: req.body.product_id})
if (!product) {
    return res.status(http.statusNotFound).json({
        errors: [{ msg: "Invalid product id" }]
    })
}

let cart = user.cart.slice()
cart.push({ product_id: product._id, quantity: req.body.quantity })

user.cart = cart // this is the line that causes the error
            
await user.save()
res.json({ msg: "Product added to cart" })

I am getting an error when I try to push a JSON object with product_id and quantity into a user’s cart. There is a circular reference in the JSON object that’s causing it, but I can’t figure out what I did wrong. The error stack trace doesn’t really Here is the error I get:

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    |     property '__parentArray' -> object with constructor 'Array'
    --- index 0 closes the circle
    at stringify (<anonymous>)

If I uncomment, user.cart = cart line, then I don’t get this error. The moment I try to update the cart field, I get this error. I tried updating the cart field in different formats, but all failed.

I tried directly pushing to the cart field, yet I get the same error:
user.cart.push({ product_id: product._id, quantity: req.body.quantity})

I also tried to directly update the cart with a MongoDB query, but I still get the same error:

await User.updateOne(
    {_id: user._id}, 
    { $push: { cart: { product_id: product._id, quantity: req.body.quantity } }}
)

“:nth-child” is unsafe in reactjs + material ui why?

I am trying to create a simple style component but getting below error.I am using material ui + reactjs

export const DGridCol = styled(Box)(({ theme }) => ({
  width: "calc(100% / 5 - 16px)",
  marginBottom: "24px",
  marginRight: "20px",
  "&:last-child": { marginRight: "0px" },
  [theme.breakpoints.down("md")]: {
    width: "calc(100% / 2 - 8px)",
    marginBottom: "15px",
    marginRight: "16px",
    "&:last-child": { marginRight: 16 },
    "&:nth-child(2),&:nth-child(4),&:nth-child(6)": { marginRight: 0 }
  }
}));
export default function App() {
  return (
    <DGrid>
      <DGridCol>MUI example</DGridCol>
    </DGrid>
  );
}

here is my code
https://codesandbox.io/s/lingering-thunder-l5b6l6?file=/src/App.tsx:281-815

Is there any way to turn off these warning because reactjs is Client side rendering
enter image description here

Implement a function called multiples that accepts two numbers: x and n

Okay, So I’m pretty new to this and I have literally run my Javascript code in the Console which first worked with a variable and then I ended up here and changed it to a constant because it still wasn’t working in Hackerrank where I am doing a code challenge? What am I doing wrong? I keep getting syntax errors.

function multiples(x, n){
var arr[];
for (var i = 1; i <= n; ++i)
arr.push(x * i);
return arr;
}

SyntaxError: Unexpected token '['

Are symbols acting like objects in JavaScript?

Are symbols acting like objects in JavaScript or a Symbol object is being created under the hood in the following example:

const symbol = Symbol();

Symbol.prototype.sayHello = function () {
  console.log("sayHello");
};

symbol.sayHello(); //"sayHello"

I know that in JavaScript the function Symbol cannot be invoked with the keyword “new”. But can it be done behind the scenes? I already know that when we use methods on primitive values like this:

console.log("333".startsWith("33")); //true

A String object is being created and the method String.prototype.startsWith is being invoked. After that, the object is being garbage-collected. But is it the same case when we work with symbols? Even though we cannot explicitly invoke the function Symbol as a constructor function?

Cookies are not getting set when running with –host option in official SvelteKit example

I am trying offical SvelteKit example https://realworld.svelte.dev/.
Its code is hosted at https://github.com/sveltejs/realworld

login and everything works fine when I run npm run dev
but when I run npm run dev -- --host then login does not work.

cookies.set('jwt', value, { path: '/' });

This is not working so cookies are not getting set so login is not working.

How can I make login working when using --host option?

Need replace querySelector to querySelectorAll in slider

> sorry for my english)

In a nutshell: need replace querySelector with querySelectorAll and keep the functionality in slider (const sliderItems)

Hi all, I have a slider and it seems to work fine, but only if I use querySelector. For further manipulation – I need to select all elements, (querySelectorAll). It seemed to be no big deal, but the slider stops working when I use querySelectorAll. I’m asking for help, because I have no idea how to fix it, without loss of functionality 🙂

JavaScript:

const slider = document.querySelectorAll('.slider'),
      sliderItems = document.querySelector('.slider__items'), 
      prev = document.querySelectorAll('.prev'),
      next = document.querySelectorAll('.next');

function slide(wrapper, items, prev, next) {
  let posInitial,
      slides = items.querySelectorAll('.slider__items *'),
      slidesLength = slides.length,
      slideSize = items.querySelectorAll('.slider__items *')[0].offsetWidth,
      firstSlide = slides[0],
      lastSlide = slides[slidesLength - 1],
      cloneFirst = firstSlide.cloneNode(true),
      cloneLast = lastSlide.cloneNode(true),
      index = 0,
      allowShift = true;

  //Set offset to first slide
  const slideWidth =  window.getComputedStyle(firstSlide);
        console.log(slideWidth.width);
        items.style.left = `-${slideWidth.width}`;
  
  // Clone first and last slide
  items.appendChild(cloneFirst);
  items.insertBefore(cloneLast, firstSlide);
  wrapper.forEach(item => {
    item.classList.add('loaded');
  });

  // Click events
  prev.forEach(item => {
    item.addEventListener('click', function () { shiftSlide(-1) });
  })
  next.forEach(item => {
    item.addEventListener('click', function () { shiftSlide(1) });
  })

  // Transition events
  items.addEventListener('transitionend', checkIndex);

  function shiftSlide(dir, action) {
    items.classList.add('shifting');
    
    if (allowShift) {
      if (!action) { posInitial = items.offsetLeft; }

      if (dir == 1) {
        items.style.left = (posInitial - slideSize) + "px";
        index++;     
      } else if (dir == -1) {
        items.style.left = (posInitial + slideSize) + "px";
        index--;  
      }
    };
    
    allowShift = false;
  }
    
  function checkIndex (){
    items.classList.remove('shifting');

    if (index == -1) {
      items.style.left = -(slidesLength * slideSize) + "px";
      index = slidesLength - 1;
    }

    if (index == slidesLength) {
      items.style.left = -(1 * slideSize) + "px";
      index = 0;
    }
    allowShift = true;
  }
}

slide(slider, sliderItems, prev, next);

HTML:

<div class="slider">
  <div class="slider__wrapper">
    <div class="slider__items">
      <span class="slider__slide">Slide 1</span>
      <span class="slider__slide">Slide 2</span>
      <span class="slider__slide">Slide 3</span>
      <span class="slider__slide">Slide 4</span>
      <span class="slider__slide">Slide 5</span>
      <span class="vertical slider__slide vertical">Slide 6</span>
    </div>
  </div>
  
  <a id="prev" class="control prev"></a>
  <a id="next" class="control next"></a>
</div>

CSS:

.slider {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2);
}

.slider__wrapper {
  position: relative;
  width: 600px;
  height: 400px;
  overflow: hidden;
  z-index: 1;
}

.slider__items {
  display: flex;
  position: absolute;
}

.slider__items.shifting {
  transition: left 0.2s ease-out;
}

.slider__slide {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 600px;
  height: 400px;
  cursor: pointer;
  transition: all 1s;
  background: #FFCF47;
  border-radius: 2px;
}

.slider.loaded .slider__slide:nth-child(2),
.slider.loaded .slider__slide:nth-child(7) {
  background: #FFCF47;
}
.slider.loaded .slider__slide:nth-child(1),
.slider.loaded .slider__slide:nth-child(6) {
  background: #7ADCEF;
}
.slider.loaded .slider__slide:nth-child(3) {
  background: #3CFF96;
}
.slider.loaded .slider__slide:nth-child(4) {
  background: #a78df5;
}
.slider.loaded .slider__slide:nth-child(5) {
  background: #ff8686;
}

.control {
  position: absolute;
  top: 50%;
  width: 50px;
  height: 50px;
  background: #fff;
  border-radius: 50px;
  margin-top: -20px;
  box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.3);
  z-index: 2;
}

.prev,
.next {
  background-size: 22px;
  background-position: center;
  background-repeat: no-repeat;
  cursor: pointer;
}

.prev {
  background-image: url(https://cdn0.iconfinder.com/data/icons/navigation-set-arrows-part-one/32/ChevronLeft-512.png);
  left: -20px;
}

.next {
  background-image: url(https://cdn0.iconfinder.com/data/icons/navigation-set-arrows-part-one/32/ChevronRight-512.png);
  right: -20px;
}

.prev:active,
.next:active {
  transform: scale(0.8);
}

I tried to replace querySelector with querySelectorAll myself, but then I got a bunch of errors and the script didn’t work 🙂

How to loop with index check and double bangs?

The following works very well, as an alternative for length check.

import { range } from 'lodash';

const items = range(10);

let i = -1;

while (items[++i] != undefined) {
  console.log(items[i]);
}

but if it is changed to while (!!items[++i]) it hangs. Is there a way to keep this short hand way of boolean checking without explicit undefined check?

let i = -1;

while (!!items[++i]) {
  console.log(items[i]);
// this seems not terminating
}

Activate checkbox with a jinja ID from ajax database list

I am working on my first web dev project and I am completely flummoxed by this error. My html contains a jinja loop to iteratively generate checkboxes with unique ids. I would like to tick checkboxes based on a list of IDs returned from my database with AJAX through jquery, but it seems theres some weird jinja – jquery interaction that means the checkbox ids are not working.

js file example section:

$(document).ready(function () {
$("#selectAll").click(function () {
// get checkbox ids from database as a list: 
        $.ajax({
            url: "/api/get-availability",
            type: 'GET',
            data: {
                "Pro": $("#prochoice").text(),
                "Date": [day, month, year].join('/')
            },
            success: function (data) {
                for (let d of data) {
                    $("#" + d).prop('checked', true); // iterate over ids for checkboxes
                }
            }
        });
    }

html file for checkboxes:

<!-- choose time -->
<div class="mt-3 mb-0 m-2" style="text-align: left;"><label>Choose availability:</label>
<!-- iterate over checkboxes using jinja -->
<div class="container row justify-content-md-center">
    {% for tt1, tt2 in time %}
    <div class="col-md-6">
          <div class="custom-control custom-checkbox m-0 mt-1" style="text-align: left;">
          <input type="checkbox" name="timescheck" class="custom-control-input" id="{{ tt1 }}">
          <label class="custom-control-label" for={{ tt1 }}>{{ tt1 }} - {{ tt2 }}</label>
        </div>
   </div>
{% endfor %}
</div>

api call

@api.route('/get-availability', methods=['GET'])
def get_availability():
        return ['16:00', '16:30', '17:00']

render html template

@website.route("/availability-admin")
def availadmin():

    # Set the total time list for checkboxes here:
    t1 = ['15:00', '15:30', '16:00', '16:30', '17:00', '17:30'] 
    t2 = ['15:30', '16:00', '16:30', '17:00', '17:30', '18:00'] 
    env = jinja2.Environment()
    env.globals.update(zip=zip)
    time = zip(t1, t2)

    return render_template('availabilty-admin.html', time = time)

Smiley Button not incrementing. Using a map with React hooks

I am trying to provide each item in items with a smiley counter that increments when the smiley button is clicked.

Does anybody have any idea why the smile count does not render an incremented value? Is it because the count is repeatedly getting set to zero? I would like to perform the newStateVariables function only once by wrapping it in a useEffect, however, I get an error message when I do that because it is against hook rules to put a useState (that is being called by CreateItemState()) in a useEffect. Any suggestions?

I would also like to note that the rendering works as expected if I pass newStateVariables as a guard to the useEffect containing setStateVariables (in bold). Unfortunately, this solution is not feasible because it causes continuous rendering which uses up my CPU usage/crashes my computer.

const CreateItemState = () => {
  const [countSmile, setCountSmile] = useState(0);
  const [countFrown, setCountFrown] = useState(0);
  return [countSmile, setCountSmile, countFrown, setCountFrown];
}

function ItemPosts({ items }) {
  const [stateVariables, setStateVariables] = useState([]);
  items = items.slice(0, 10);
  console.log(items)

  const newStateVariables = items.map((item) => { // Want this to run one time but can't put useState in useEffect
    const values = CreateItemState();
    const [countSmile, setCountSmile, countFrown, setCountFrown] = values;
    return {item, countSmile, setCountSmile, countFrown, setCountFrown};
  });

  **useEffect(() => {
    setStateVariables(newStateVariables);
    console.log('Component re-rendered');
  }, []);**

Button Container

    <Button icon="smile outline" content={countSmile} size="small" floated='left' onClick={() => setCountSmile(countSmile + 1)}>
    </Button>