logo
Tags down

shadow

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 (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setTimeout(() => setCount(count + 1), 2000)}>
        Delayed Counter (basic)
      </button>
      <button onClick={() => setTimeout(() => setCount(x => x + 1), 2000)}>
        Delayed Counter (functional)
      </button>
      <button onClick={() => setCount(count + 1)}>Immediate Counter</button>
    </div>
  );
}

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);
            setAddingInProgress(true);
            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 {
                selectedServicesIds.push(id);
                await updateServices(selectedServicesIds);
            }
            setAddingInProgress(false);
            console.log('set to false', loadingState);
            setLoadingState(prev => ({ ...prev, ...{ [id]: false } }));
        },
        [selectedServices]
    );

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 => ({
      ...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}>
        <label>
          <input
            type="checkbox"
            className="filled-in"
            onChange={() => handleCheckbox(id)}
            checked={checked[id]}
          />
          <span className="black-text">Checkbox{id}</span>
        </label>
      </div>
    ))


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

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) {
    console.log(id);
    if (eduState.length > 1) {
      const updatedEdus = eduState.filter(edu => edu.id !== id);
      setEduState(updatedEdus);
    }
  }

  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;
    });

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

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>
          <Form.Group as={Row}>
            <Form.Label column sm={3}>
              {`Course #${idx + 1}`}:
            </Form.Label>
            <Col sm={5}>
              <input
                type="text"
                name="name"
                onChange={e =>
                  handleEducationChange(idx, e.target.name, e.target.value)
                }
              />
            </Col>
          </Form.Group>
          <Form.Group as={Row}>
            <Form.Label column sm={3}>
              Passing Year:
            </Form.Label>
            <Col sm={5}>
              <input
                type="text"
                name="year"
                onChange={e =>
                  handleEducationChange(idx, e.target.name, e.target.value)
                }
              />
            </Col>
          </Form.Group>
        </Form>
      </span>
    </div>
  );
};

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 :
  • Add class on current menu in jQuery via window.location
  • How to remove previous button from first page and next button from last page?
  • After I login with email and password, I need to pass my email to the further page for retrieve the user data from the A
  • Intl.NumberFormat to format price in Norwegian Krone
  • Add the key value based on property in array object javascript
  • How to determine if any arrays in an object has an entry
  • Unique ID generated twice with uniqid
  • How to subset an array using another one with boolean values using lodash
  • Object.assign(...as) changes input parameter
  • How can I use async lambdas without a try/catch block and still have custom error messages?
  • How do I add a property to all objects in an array based on current property using rxJS
  • What is the right name of event handler? onClick or handleClick?
  • Closing a DIV will closing another related input
  • fullcalendar two-shift calendar, coloring weeks
  • onClick with multiple functions
  • can't combine script and php div.innerHTML += "<form action='\"{{route('stock.store')}}\"' method='pos
  • Image transition CSS/JavaScript
  • How to create nested child objects in JavaScript from array?
  • React component not re-rendering with state update
  • React Axios - JSON Get response isn't displaying from render() - Riot API
  • How to put a timer for specific id on HTML
  • Pushing first character at last and returning the string
  • Show all values returned from an AJAX request
  • Transform array of objects having HTML within its properties into JSX-elements
  • How to edit div content on button click using html and javascipt or jquery?
  • jQuery form, check if radio is checked
  • How can I check if a value exists inside an array of objects in javaSript?
  • How to calculate array by given points labels?
  • How to prevent parallel execution of asynchronous init method in JavaScript?
  • Same height of elements in different lists in 2 column CSS
  • why does JSON.stringify() adds extra ' ' around the object
  • Replace favicon on youtube with a jquery string in console
  • reactjs if/else inside object.keys
  • find the first pre tag in a div and then delete the leading white spaces
  • Isn't React's immutable element creation and rendering mechanism terribly inefficient?
  • Javascript : calling method to fill innerHTML not working, the method is kind of "stringyfied" instead of bein
  • Invalid left assignment in document.getElementById
  • Webpack won't treeshake unused named export objects (using Create React App)
  • How to get the average value of array in JavaScript
  • pass a parameter into a javascript file
  • How to know if a string includes at least one element of array in Javascript
  • I am writting documnt to my marklogic Document database but geeting an error "write single document: cannot process
  • How to create and open bootstrap dropdown manually?
  • How to test default exported javascript module in Jest?
  • Finding a div in a text variable with jQuery
  • How to check if a certain property is undefined in NodeJS
  • Javascript OR (||) with ternary operator
  • How would you add non breaking space and ect. in the text?
  • CSS or JS - Hide old elements from html
  • create an array of promises for Promise.all
  • Session Storage not reset when iFrame closed
  • I have a Range input in order to change the color, but it doesn't work
  • Recursive function prints correct final result inside the loop but then is undefined outside
  • div value is undefined in jQuery
  • Javascript Objects, For loop mutlidimensional array to create new object
  • What happens when some functions take a long time? Are they asynchronous?
  • Extract image src attribute from thousands of links - Task automation using JavaScript
  • Collapsible not Working [JSFiddle demo Included]
  • Google Script to Fill out HTML Form
  • JSON manipulation, rewriting a new array appending data as children
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org