Parent component does not rerender after updating its state through child component

I checked some of the threads about this and tried to fix it, but no succes yet.

I have a parent and a child component. In the parent component, I declare a state and pass the function to update this state on to my child component.

  function ProfileGallery() {
  const [selectedPet, setPet] = useState(null);
  const [filterText, setFilterText] = useState('');
  const [pets, setPets] = useState([]);
  const [componentState, setState] = useState('test');

  const updateState = (state) => {
        setState(...state);
      };

  return (
       <PetInformation
                selectedPet={selectedPet}
                componentState={componentState}
                triggerParentUpdate={updateState}
              />
);
}

In my child component, I do the following:

function PetInformation({ componentState, triggerParentUpdate, ...props }) {
  const [status, setStatus] = useState('Delete succesful');
  const { selectedPet } = { ...props } || {};
  const updatedComponentState = 'newState';

  useEffect(() => {
    if (status === 'Delete pending') {
      deletePet(selectedPet).then(() => setStatus('Delete succesful'));
    }
  }, [status]);

  const handleDelete = () => {
    setStatus('Delete pending');
  };

return (
    <button
            className="btn btn-primary pull-right"
            onClick={() => {
              handleDelete();
              triggerParentUpdate(updatedComponentState);
            }}
            type="button"
          >
            Delete Pet
    </button>

There’s of course more code in between, but this shows the gist of what I’m trying to achieve. I want to delete an item I selected in my gallery and have that delete reflected once I click the delete button -> my ProfileGallery needs to re-render. I’m trying to do this by passing that function to update my state on to the child component. I know JS won’t consider state changed if the reference remains the same, so that’s why I am passing a new const updatedComponentState on, since that should have a different reference from my original componentState.

Everything works, the item gets removed but I still need to manually refresh my app before it gets reflected in the list in my gallery. Why won’t ReactJS re-render my ProfileGallery component here? Isn’t my state getting updated?

Toggle elements with same classnames independently with pure js (tags on blog posts)

I have this jquery that I want to find a pure JS solution for – when pressing a button, it toggles the tags on blog each posts independently:

 $('.tags').hide();
    $('.toggle-tags').click(function(event) {
        $(this).closest('.info').find('.tags').slideToggle(400)
    });

Ideally I want to achieve what I’ve got from the following js I use for a nav-menu. I’m aware that I’ll need to use querySelectorAll() instead, but also loop it through the elements, right?

var tagswrap = document.getElementById("tags");
var height = tagswrap.clientHeight;
tagswrap.style.height = 0;

function toggleClass(tagswrap, height) {
    tagswrap.style.height = height + "px";
    var tagswrap = document.getElementById("tags");
    var className = "active";
    if (!tagswrap || !className) {
        return;
    }
    var classString = tagswrap.className,
        nameIndex = classString.indexOf(className);
    if (nameIndex == -1) {
        classString += " " + className;
    } else {
        classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length);
        tagswrap.style.height = 0;
    }
    tagswrap.className = classString;
}
var buttonTags = document.getElementById("toggle-tags");
buttonTags.onclick = function () {
    toggleClass(tagswrap, height);
};

the structure of each blog post:

<article>
.. blog text here ..
  
<div class="info">
  <div class="info-content">
    <div class="right">
      <div class="toggle-tags">show tags</div>
    </div>
    
  </div>
  
  <div class="tags">
    <a href="#">text</a>
    <a href="#">quote</a>
    <a href="#">testing</a>
  </div>
  
</div>
  
</article>

I’m still too new to js know how to implement this. Any pointers or suggestions would be great.

displaying data in modal using ajax in codeigniter not working

i have an html table in codeigniter which has different rows, when user clicks on any id of the table it should open a modal and display the details, id did the following:

in controller:

    public function select(){
                        
  $id = $this->segments->uri(3);
  $data['details'] = $this->user->selectdetails($id);

  
                        }

in model:

public function selectdetails($id) { 
$this->db->select('*'); 
$this->db->where('id', $id); 
$this->db->from('consignments'); 
$query = $this->db->get(); 
$result = $query->result(); 
return $result; 
}

and finally in view:

$(".detailsbtn").click(function(e){
  var modal = document.getElementById("details");
        e.preventDefault();
        var id = $(this).attr('id');
        $.ajax({
          type:'POST',
          url:'<?php echo base_url()?>homecontroller/select/'+id,

          success:function(data){
             $('#details').find('.modal-content').html(data);
             $('#details').modal('show');
          }
       });

    });
<td>

  <input id="<?= $val->id?>" class="detailsbtn btn-sm btn-info" type="button" value="<?= $val->awb?>">
  
</td>


   
 <div class="modal-body">
   <div class="container-fluid">
     <div class="row">
       <div class="col-md-12">




<?php foreach($details as $de){?>
<?php echo $de->consignee;?>
<?php }?>

       </div>
     </div>
   </div>
 

however this is giving me error,page not found error, can anyone please tell me how to fix this, thanks in advance

Laravel – Uncaught TypeError: Cannot read properties of null (reading ‘value’)

I’m trying to use lightpick datepicker on my application. Unfortunately this works when I don’t follow standards, and doesn’t work when I do.
Blade :

@section('page_script')
    <script src="{{ url('js/themeFiles/moment/moment.min.js') }}"></script>
    <script src="{{ url('js/themeFiles/lightpick/lightpick.js') }}"></script>
    <script src="{{ url('js/custom/datePicker.js') }}"></script>
    <script src="{{ url('js/custom/planningStats.js') }}"></script>
@endsection

@section('content')
    @include('planning.partials.planningStatsForm')
@endsection

datePicker.js:

var picker = new Lightpick({
    field: document.getElementById('ddebut_picker'),
    secondField: document.getElementById('dfin_picker'),
    repick: true,
    lang: 'fr',
    singleDate: false,
    selectForward: true
});

Error (if I use the above code) :
enter image description here

If I use the script tags inside @section('content') and do no use separate @section('page_script') section then everything works perfectly. But for the current code, it doesn’t work. I haven’t changed anything in the js, controller, blade or model.

Cannot set properties of undefined (setting ‘listeners’) mock socket library when mocking web socket in Cypress

I have a mock server in my cypress test file

const getServer = () => {
    return new Cypress.Promise(resolve => {
        const mockServer = Server('wss://notifier.shoutout.social/')

        let mockSocket
        mockServer.on('connection', (socketHandle) => {
           resolve(socketHandle)
        })
    })
}
const socketPromise =  getServer()

Every time I want to send a message to my client from my web socket I am calling it with a cy.wrap using

cy.wrap(socketPromise).then((mockSocket) => {
    mockSocket.send({fixture: 'WebSocketMocks/WebSocketInitialised.json'})
})

But I get this error coming from the mock socket library in my stack trace

 var EventTarget = function EventTarget() {
> 742 |   this.listeners = {};
      | ^
  743 | };

Cheers 🙂

Select currency and show commas and/or decimals in the input

I have a select (currency) and an input (amount)

The input has to show thousands separators (commas ,) for all the currencies and two decimals .00 for all the currencies as well (except for JPY) in real time while the user is typing.

Example input: (JPY) 123456789

Desired result: 123,456,789

Example input: (USD) 123456789.94

Desired result: 123,456,789.94

What I’ve tried:

Using toLocaleString():

$("#valueInput").on('keyup',function(){
    $("#valueInput").val($("#valueInput").val().toLocaleString());
});

Using split and replace:

$("#valueInput").on('keyup',function(){
    $("#valueInput").val($("#valueInput").val().split(',').join(''));
    $("#valueInput").val(($("#valueInput").val()).replace(/B(?=(?:d{3})+(?!d))/g, ","));
    $("#estimatedValue").val($("#estimatedValueSelect option:selected").text() + " " + $("#valueInput").val());
});

Using toLocaleString() & specifiying a format:

$("#valueInput").on('keyup',function(){
    var value = $("#valueInput").val();
    $("#valueInput").val(value.toLocaleString('en'));
});

None of them worked.

Full code:

$('#valueSelect').on('change', function(){
    if(this.value === 'JPY') {
        $("#valueInput").removeAttr("pattern");
        $("#valueInput").removeAttr("placeholder");
        $("#valueInput").removeAttr("min");
        $("#valueInput").removeAttr("step");
        $("#valueInput").attr("pattern","[0-9]");
        $("#valueInput").attr("title","Numbers only");
        $("#valueInput").attr("placeholder","1000");
    } else {
        $("#valueInput").removeAttr("placeholder");
        $("#valueInput").attr("pattern","^d+(?:.d{1,2})?$");
        $("#valueInput").attr("placeholder","0.00");
        $("#valueInput").attr("min","0");
        $("#valueInput").attr("step","0.01");
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>


<div class="col-sm">
    <div class="row">
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <select  id="valueSelect" class="selectpicker"  aria-label="Currency">
                    <option value="JPY" selected>JPY</option>
                    <option value="USD">USD</option>
                    <option value="EUR">EUR</option> 
                </select>
            </div>
            <input id="valueInput" class="form-control" aria-label="Estimated Value" type="number" placeholder="1000" name="price" pattern="[0-9]" required>
        </div>
    </div>
</div>

I have also implemented the validation part and it works partially, what I can’t get to work is displaying a comma , and period . in real time while the user is typing with the restrictions mentioned above.

Check multiple conditions JavaScript OR [duplicate]

Probably a daft question – but can anyone explain why this doesn’t result in both ‘e’ and ‘u’ being logged to the console?

console.log(resultArray);

for (let i = 0; i < resultArray.length; i++)
{

  if (resultArray[i] === ('e'||'u')) {
  console.log(resultArray[i]);
  }

}

CONSOLE OUTPUT:

[ ‘o’, ‘e’, ‘o’, ‘u’, ‘u’, ‘u’, ‘a’, ‘e’, ‘e’ ]

e

e

e

How to access next object in an array by incrementing

let myQuestions = [
    {
        question: "What's 2+2?",
        answers: [
            { text: "4", correct: true },
            { text: "2", correct: false },
            { text: "10", correct: false },
            { text: "1", correct: false },
        ],
    },
    {
        question: "What's 10+10?",
        answers: [
            { text: "20", correct: true },
            { text: "2", correct: false },
            { text: "18", correct: false },
            { text: "0", correct: false },
        ],
    },
];
function startQuiz() {
    container.style.visibility = "visible";
    btn_start.style.visibility = "hidden";
    showQuestion(myQuestions[0]);
}
function showQuestion(questionAndAnswers) {
    const shuffledAnswers = _.shuffle(questionAndAnswers.answers);
    questionTag.innerText = questionAndAnswers.question;
    answerTag[0].innerText = shuffledAnswers[0].text;
    answerTag[1].innerText = shuffledAnswers[1].text;
    answerTag[2].innerText = shuffledAnswers[2].text;
    answerTag[3].innerText = shuffledAnswers[3].text;
}
function nextQuestion() {
    showQuestion(myQuestions[0]);
    
}

First question gets called when I press start quiz and it access my first object in my array, how do I make the function next question work which basically access the next object by incrementing so lets say I add question 3 it keeps on going.

Disable specific rows in react-table

I am using react-table v7.6.3 where I am allowing users to edit some data in the table. I intend to use WebSockets to prevent another user from editing the same row of data that a user is already editing. For that, I need to disable rows in react-table. Can this be achieved?

enter image description here

Javascript – forEach with promise.all not working

I tried to handle promises with for each but not working

I assume it will log something because of console.log(result).

Why is it not working?

It only logs

All done (54) [ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ]
          let promises = [];
                  mkt.forEach(async function (marketItem, index) {
                    promises.push(() => {
                      context.program.account.chain
                        .fetch(sth)
                        .then((result) => {
                console.log(result)
                        });
                    });
                  });
          Promise.all(promises)
                    .then(results => {
                      console.log('All done', results);
                    })
                    .catch(e => {
                      // Handle errors here
                    });

How to close popup and redirect to parent window?

Let there be three windows.

GrandParent->parent->child.

GrandParent opens parent and parent opens child.

In our case child closes automatically and returns to parent. but when parent is closed it doesn’t return to GrandParent instead it goes to another tab.

I already tried the solution of creating a function in grandparent and calling it in parent. But it doesn’t work.

Using prevState Callback function in UseState react Hook

I have some array of products inside filteredProducts variable and wanted to sort them according to the price and newly added products.
When using prevState like this without having { } in the callback function, the code runs fine.

useEffect(() => {
    if(sort === "newest") {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a, b) => a.createdAt - b.createdAt)
        );
    }
    else if (sort === "asc") {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a ,b) => a.price - b.price)
        );
    }
    else {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a, b) => b.price - a.price)
        );
    }
}, [sort]);

But when using { } for the prevState callback function like this

if(sort === "newest") {
        setFilteredProducts((prevState) => {
            [...prevState].sort((a, b) => a.createdAt - b.createdAt)
        });
    }

, it is just throwing error in console.