Tags down


UseState shows previous value always

By : Davit Petrosyan
Date : August 02 2020, 07:00 AM
I hope this helps . accountId won't have been updated this render. You have to wait for the next render for it to be updated. accountId only gets populated at the top of the function component when useState is called. You're in the middle of the render. If you need the actual value, keep pulling it out of e.currentTarget.value.
code :

Share : facebook icon twitter icon

useState hook, setState function. Accessing previous state value

By : Dave
Date : March 29 2020, 07:55 AM
it should still fix some issue If the next state value depends on the previous value, as in this example of an increment button, it's better to use the functional version of setState (setCount(prevCount => prevCount + 1)).
You can run into errors if you're passing the setter function into a callback function, like an onChange or HTTP Request response handler.
code :
import React, { useState } from "react";
import ReactDOM from "react-dom";

function Counter() {
  const [count, setCount] = useState(0);

  return (
      <button onClick={() => setTimeout(() => setCount(count + 1), 2000)}>
        Delayed Counter (basic)
      <button onClick={() => setTimeout(() => setCount(x => x + 1), 2000)}>
        Delayed Counter (functional)
      <button onClick={() => setCount(count + 1)}>Immediate Counter</button>

const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);

React useState didn't catch previous state

By : user3142669
Date : March 29 2020, 07:55 AM
Hope that helps I have some troubles with updating state in my component: i got few services which can be selected and selection, starts async loading this service, so i want to show some loading state, but when there is more than one service and i select both ( pretty fast ) i'm getting wrong previous state , I think this will work
code :
    const onSelect = useCallback(
        async (id: string) => {
            const selectedServicesIds = selectedServices.map(service => service.id);
            console.log('set to true', loadingState);
            setLoadingState(prev => ({ ...prev, ...{ [id]: true } }));
            // set to true {0: false, 1: false}
            // actual loading state {0: true, 1: false}
            // click on second service
            // set to true {0: false, 1: false}
            // actual loading state {0: false, 1: true} <-- there is need to be {0: true, 1: true}

            if (selectedServicesIds.includes(id)) {
                selectedServicesIds.splice(selectedServicesIds.findIndex(serviceId => serviceId === id), 1);
                await updateServices(selectedServicesIds);
            } else {
                await updateServices(selectedServicesIds);
            console.log('set to false', loadingState);
            setLoadingState(prev => ({ ...prev, ...{ [id]: false } }));

Using useState hooks to update based on the previous state successively

By : Blake Ruddock
Date : March 29 2020, 07:55 AM
it fixes the issue I'm trying to enable button if both the checkboxes are checked, I have nonworking stackblitz link , You can simply check the state of both checkbox values.
code :
  const isDisabled = !(checked.checkbox1 && checked.checkbox2)
  const checkDisable = isDisabled ? 'disabled' : ''
function App() {
  const length = 6;
  1️⃣ Generate the initial checkbox states - this prevents un/controlled component error.
  const initialCheckboxes = Array
    .from({ length }, (_, i) => i + 1)
    .reduce((acc, id) => (acc[id] = false, acc), {})

  const [checked, toggleCheckbox] = useState(initialCheckboxes);
  const [isDisabled, setIsDisabled] = useState(false)

  const handleCheckbox = id => {
    toggleCheckbox(previous => ({
      [id]: !previous[id]

  2️⃣ Update the disable state when the checkbox is selected.
  useEffect(() => {
      Enable when all checkboxes are not checked - 
    setIsDisabled(!Object.values(checked).every(_ => !!_))
  }, [checked])

  3️⃣ Dynamically generate checkboxes
  const checkboxElements = Array.from({ length }, (_, i) => i + 1)
    .map(id => (
      <div key={id}>
            onChange={() => handleCheckbox(id)}
          <span className="black-text">Checkbox{id}</span>

  return (
        <a className={isDisabled ? 'disabled' : ''} href="#!">
          Next Step

React useState hook does not shows correct state of array

By : user3521998
Date : March 29 2020, 07:55 AM
will be helpful for those in need You are depending the index of the item, but indexes are changing when you add or remove elements, so they are not reliable.
You need to generate an automatic unique id when creating a new education. For example uuid package is popular for this task.
code :
import React, { useState } from "react";
import EducationInput from "./EducationInput";
import Button from "react-bootstrap/Button";
import uuidv4 from "uuid/v4";

function Education(props) {
  const blankEdu = { id: "", name: "", percentage: "", year: "" };
  const [eduState, setEduState] = useState([{ ...blankEdu }]);

  const addEducation = () => {
    setEduState([...eduState, { ...blankEdu, id: uuidv4() }]);

  function handleRemove(id) {
    if (eduState.length > 1) {
      const updatedEdus = eduState.filter(edu => edu.id !== id);

  const handleEducationChange = (id, field, value) => {
    console.log(field, value);
    let updatedEducations = eduState.map(edu => {
      if (edu.id === id) return edu;

      edu[field] = value;
      return edu;

  return (
      <div className="shadow p-3 mb-5 bg-white rounded">
        Final Step: Education
      {eduState.map(val => (
        <div key={val.id}>
          {eduState.length > 1 ? (
            <Button variant="danger" onClick={() => handleRemove(val.id)}>
              Remove Course
          ) : null}
      <Button variant="outline-info" onClick={addEducation}>
        Add New Degree
      <br />
      <br />
      Educations in json:{JSON.stringify(eduState)}

export default Education;
import React from "react";
import Form from "react-bootstrap/Form";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";

const EducationInput = ({ idx, handleEducationChange }) => {
  return (
    <div key={`edu-${idx}`} id={`edu-${idx}`}>
      <span className="border border-success">
          <Form.Group as={Row}>
            <Form.Label column sm={3}>
              {`Course #${idx + 1}`}:
            <Col sm={5}>
                onChange={e =>
                  handleEducationChange(idx, e.target.name, e.target.value)
          <Form.Group as={Row}>
            <Form.Label column sm={3}>
              Passing Year:
            <Col sm={5}>
                onChange={e =>
                  handleEducationChange(idx, e.target.name, e.target.value)

export default EducationInput;

EditText values are not reflected it shows previous value but when you print getText of Editext it shows correct value

By : win311
Date : March 29 2020, 07:55 AM
may help you . You are not getting value in edit text because ViewPager is not refreshed, rather its GUI is not refreshed, programatically when you change the text it is changed, and you are getting that, so now you only need to notify the ViewPager or refresh its view. If notifydatasetchanged not working then try setting adapter once again...
Related Posts Related Posts :
  • How to add objects within another array of object at alternate position?
  • Integrate webSDK with jQuery Inside Vue Component?
  • How to set a value for a select options based on it's index number?
  • How to create new unique id every time in JavaScript?
  • How to merge and distribute the first array over the second one in JavaScript?
  • React js does not recognize me map method
  • React is setstate messing up my algorithm?
  • GAS: HtmlService.getUserAgent() returns null when using V8
  • How to pass parameters from one component to another in router.push() (Vue.js)?
  • How to convert single digit integer into double digit [Javascript]
  • how to input numbers using buttons in to a textbox
  • Nest can't resolve dependencies of custom service
  • Updating only one property inside an array of objects react
  • How to attribute value to jquery click function
  • Call 'created' function from 'methods' in VueJS after page is loaded
  • How to separate longitude and latitude from OpenLayers coordinates
  • how to filter data in specific days
  • How to call action in react before the first load of page?
  • How to add data validation list in excel using javascript
  • Binary addition algorithm using quotient and reminder
  • Need help to understand Vue.js function
  • Is there a way of running tests within testcafe without it automatically inserting local host infront of the URL
  • How to groupBy an attribute inside the second array with javascript
  • Scrapy only scraping the first two pages
  • JavaScript submits form despite return false statement
  • JavaScript Limit Drop Down Menu To Number In Input
  • JavaScript anonymous function parameters and calling arrangement
  • 'this' returns undefined in extended Classes in Javascript
  • Jquery validation error displayed on "label". How to fix it?
  • Firebase Analytics: Can I check if a Firebase Javascript Analytics event was logged before firebase updates?
  • Why doesn't the .remove() method also affect the variable it's being set on?
  • React hooks error: Rendered more hooks than during the previous render
  • How to create a completely new Keyword in JavaScript?
  • When summing values from 2 arrays how can I cap the value in the new array?
  • A pop up window to login in
  • How to push spacebar action to array
  • How do i highlight a specific table row depending on the url
  • Truly Weak Reference Event Emitter / Dispatcher: is it possible?
  • Conditionally render a a background image based on current view using React Router
  • Can not retrieve component template while routing
  • How to keep the checkbox status after refreshing the page
  • Array of Object - divide information as per values in it
  • Calculating body style height (for horizontal scroll) in javascript not working
  • How to exclude certain values from randomly generated array
  • Change colour of selected <li>
  • Formatting date object in an Array with moment is giving an unexpected result
  • combineLatest operator alternative
  • 'object' is never reassigned. Use 'const' instead
  • What does the spread operator in ES6 convert to in older JavaScript? Is it costlier than array.concat?
  • Get duplicates in array of strings and count number of duplicates
  • How to fix React Redux and React Hook useEffect has a missing dependency: 'dispatch'
  • Call a ajax request only if there are ajax requests added to the list
  • Using the jQuery each function to count divs with the same class
  • FInding out the Harshad number
  • angular route is not working and not changing current view
  • Callback executed before function finishes execution
  • How to create subfolder and document on Firestore web?
  • Scroll algorithm -- improving fetch and display of data
  • New To Programming World
  • Using mongorestore to insert many documents into a temp collection
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org