logo
Tags down

shadow

React not re-rendering on state change with useState


By : David Ackley
Date : July 29 2020, 03:00 PM
wish helps you You can't use that key if you're modifying the array (in any way other than just adding to it). From the documentation:
code :
let nextQuestionId = 1;

const YourComponent = props => {
    // ...
    const handleNewQuestion = () => {
      setQuestions([
         ...questions,
         <Question
            key={nextQuestionId++}
            count={questions.length}
            formData={formData}
            setFormData={setFormData}
            handleRemoveQuestion={handleRemoveQuestion}
         />
      ]);
   };

   const removeQuestion = id => {
       setQuestions(questions.filter(q => q.id !== id));
   };
};


Share : facebook icon twitter icon

React Hooks: using useState inside useEffect doesn't set the state immediately after first rendering


By : user3155031
Date : March 29 2020, 07:55 AM
seems to work fine Like class-based react components' lifecycle methods, specifically the async nature of setState, so too is the functional counterpart, the useState hook. The current value of the hook remains static during the current render cycle until updates are "flushed" and the component is re-rendered. In your useEffect hook you are trying to access the tabs state value that hasn't been "synched" yet. You should instead access the tabs response array directly if you want the value in this render cycle.
code :
useEffect(() => {
  const allPics = data.map((img, i) => {
    img.node.childImageSharp.index = i
    return img.node.childImageSharp
  })
  setAllPics(allPics)

  // get all tabs
  const tabsArray = getAllTabs(allPics);

  setTabs(tabsArray)

  // default tab when the page first loads
  setCurrentImgs(
    allPics.filter(({ fluid }) => fluid.originalName.includes(tabsArray[0]))
  )
}, []) // pass empty dependency array if you truly only want this to run on mount

How to change useState's state without re-rendering the component, but just its components


By : Marko
Date : March 29 2020, 07:55 AM
Hope that helps I took a shot at answering your question. Basically, you want to be able to calculate a value once and have it updated only when the content changes. You can do this with useEffect. The first parameter for useEffect is a function you want to happen on mount/update. It should return a function to run when your function is unmounted (if any). The second argument are the things that determine if useEffect gets ran. I put it to run when user changes value. Hopefully this is enough to get you started down the path of something. You can read more about useEffect in the docs.
code :
function Comp2(props) {
  const { user, setUser } = useContext(UserProvider);
  const { state, setState } = useState({ value: '' });

  useEffect(() => {
    console.log(user);
    // perform expensive operation
    setValue({ value: 'My expensive operation is now stored' });
    return () => {
      // Do you have anything that you would put in componentWillUnmount()?
      // Put that here
    };
  }, [user]);

 console.log(state.value);

  return (
    <div>
      {user.exists}
    </div>
  )
}

React does not change state after updating state in usestate hook (in custom function form)


By : user3295631
Date : March 29 2020, 07:55 AM
this will help I am using usestate hook in react 16.10.2, but after updating initial state using custom function in usetate hook, react does not trigger a re-render(OtherComponent is not rendered), Here is my react component: , I assume the problem is that you are mutating render?
code :
<button 
  onClick={() => setRender({ ...render, [index]: !render[index] })}
>
  change state
</button>
const CustomComponent = () => (
  <div style={{ marginLeft: 10, background: "red" }}>I'm Selected!</div>
);

function App() {
  const [people] = useState([
    { id: 0, name: "Mario" },
    { id: 1, name: "Luigi" },
    { id: 2, name: "Peach" }
  ]);

  const [selected, setSelected] = useState({});

  return (
    <div>
      {people.map(({ id, name }) => (
        <div
          style={{ display: "flex", cursor: "pointer" }}
          key={id}
          onClick={() => setSelected({ ...selected, [id]: !selected[id] })}
        >
          {name}
          {selected[id] && <CustomComponent />}
        </div>
      ))}
    </div>
  );
}
function App() {
  const [obj, setObj] = useState({ name: "Mario" });
  const change = () => {
    // The following commented code will display no change
    // obj.name = "Peach";
    // setObj(obj);
    setObj({ ...obj, name: "Peach" });
  };
  return (
    <div className="App">
      <div>{obj.name}</div>
      <button onClick={change}>Change!</button>
    </div>
  );
}

App keeps re-rendering when setting state in promise using useState in React


By : user3432068
Date : March 29 2020, 07:55 AM
I hope this helps you . I'd like to make a call to a rest endpoint, retrieve an array of items and display them in the page. , You need to move your api call inside useEffect hook:
code :
useEffect(() => {
  axios
    .get("https://reqres.in/api/users")
    .then(response => {
      console.log(response);
      setUsers(response.data.data);
    })
    .catch(function(error) {
      // handle error
      console.log(error);
    });
}, [])

React hooks - useState() is not re-rendering the UI with the new state updates


By : Barfield
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further alright, problem solved with the helpful hint from @skyboyer,
so what happened initially is, the useEffect() acts like componentDidMount() & componentDidUpdate() at the same time, that means whenever there is an update to the state, the useEffect() gets invoked, which means resetting the state with the initial data coming from the server. to fix the issue I needed to make the useEffect() renders the component only one time when it's created/rendered as opposed to rendering it every time there is an update to the state. and this is done by adding an empty array as a second argument to the useEffect() function. as shown below.
code :
 useEffect(() => {
   axios.get('...')
    .then(res => {
      setPosts(res.data)
     })
   }, [])
Related Posts Related Posts :
  • 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
  • VueJS: How can I successfully pass arrays from child to parent components
  • MongoDB schema does not insert property when using with insertOne function
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org