logo
Tags down

shadow

How to access state when component unmount with React Hooks?


By : Gilbert Vigil
Date : July 31 2020, 11:00 AM
I hope this helps . useState() is a specialized form of useReducer(), so you can substitute a full reducer to get the current state and get around the closure problem.
NoteEditor
code :
import React, { useEffect, useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "set":
      return action.payload;
    case "unMount":
      console.log("This note has been closed: " + state); // This note has been closed: 201
      break;
    default:
      throw new Error();
  }
}

function NoteEditor({ initialNoteId }) {
  const [noteId, dispatch] = useReducer(reducer, initialNoteId);

  useEffect(function logBeforeUnMount() {
    return () => dispatch({ type: "unMount" });
  }, []);

  useEffect(function changeIdSideEffect() {
    setTimeout(() => {
      dispatch({ type: "set", payload: noteId + 1 });
    }, 1000);
  }, []);

  return <div>{noteId}</div>;
}
export default NoteEditor;
import React, { useState, useEffect } from "react";
import "./styles.css";
import NoteEditor from "./note-editor";

export default function App() {
  const [notes, setNotes] = useState([100, 200, 300]);

  useEffect(function removeNote() {
    setTimeout(() => {
      setNotes([100, 300]);
    }, 2000);
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {notes.map(note => (
        <NoteEditor key={`Note${note}`} initialNoteId={note} />
      ))}
    </div>
  );
}


Share : facebook icon twitter icon

React Hooks - function inside function component passed as prop can't access state


By : BigTrunk
Date : March 29 2020, 07:55 AM
This might help you I have read about React hooks and wanted to try it on this new website I have been developing. I am trying to pass an async function as a prop. Part of the function is to set my "cities" state and console log just to see if the API works. I have been receiving "setCities is not a function" error or, cities returns undefined if I just console log it directly. I think the function can't access the {cities, setCities} state. I have tried it in class component and it works. Has anyone encountered similar situations? Below is the code sample: , useStates return an array, not an object...
So you can change
code :
const { cities, setCities } = useState([]);
const [ cities, setCities ] = useState([]);

How can I update a component's state based on its current state with React Hooks?


By : user2963493
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You can pass an updater function just like with setState. So, in this code, you'd run:
code :
setProgress(progress => ({ ...progress, [videoUrl]: "downloading" }));

React hooks: How to read & update state in hooks without infinite loops with react-hooks/exhaustive-deps rule


By : solo
Date : March 29 2020, 07:55 AM
hope this fix your issue When state is in a hook it can become stale and leak memory: , Use the functional form of the state setter:
code :
const fetchData = useCallback(async () => {
  const res = await fetch(`url?page=${page}`);
  setData((data) => ([...data, ...res.data]));
  setPage((page) => page + 1);
}, [setData, setPage]);
  const mounted = useRef(false);

  useEffect(() => {
    if(!mounted.current) {
      fetchSomething();
      mounted.current = true;
    }

    return () => { mounted.current = false }
  }, [fetchSomething]);
const fetchSomething = useCallback(async () => {
  ...
}, [setData, setPage, data, page]);

update state of child component from parent component using react hooks


By : mohyulasar
Date : March 29 2020, 07:55 AM
may help you . In react if you want something to change in the Child component depending on the Parent component you have to lift the state up to the parent component. If you want to differentiate between what should be state and what should be props and where should the state reside then its simple to figure out.
State: Keep the state (message) in the component where the data will change. In this case CreateChannel component.
code :
import React from "react";
import { Message } from "semantic-ui-react";


function RespMessages({message}) {
  return (
    <Message positive>
      <Message.Header>{message}</Message.Header>
    </Message>
  );
}

export default RespMessages;
import React, { useState } from "react"
import { Container } from "semantic-ui-react"

function CreateChannel() {
    const [message, setMessage] = useState("")
    return (
        <Container>
            <RespMessages message={message} />
        </Container>
    )
}

export default CreateChannel

How to keep React component state between mount/unmount?


By : tryion
Date : March 29 2020, 07:55 AM
I hope this helps . The most important decision is where to keep the state when the component unmounts.
Some options:
Related Posts Related Posts :
  • 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
  • How to extend localStorage across devices (without DB)
  • How to do pre increment without using ++I?
  • Retrieve filterViewId from batchUpdate request addFilterView
  • What is the corresponding instanceof target for text nodes?
  • How to Test the API by Token on Postman?
  • How to set Bootstrap dropdown menu on hover?
  • In Slate.js editor.apply(operation) is not applying "split_node" operations correctly
  • No data in GET response
  • Javascript using if else to determine array value
  • Error when I run npm install Error: 404 Not Found: 7zip-bin@~4.1.0
  • I want to modified my JSON output using JS
  • Error in Entry module not found and in webpack
  • Submit button is not submitting the form after changing the button type
  • Why is the function created is not working.?
  • How can I do day timer with javascript?
  • Tap screen to trigger autofocus with getUserMedia
  • Unable to bind html table data to mvc controller Model
  • How can I simply work around a missing JS property in an object in an object?
  • How to add anything at a specific position in a string using vanilla javascript
  • using async methods inside of array.map() in javascript
  • Math.random() vs random() in Khan Academy Computer Programming
  • Call two functions with onPress in react native
  • Use a global variable inside promise javascript
  • Turn array of objects into array of properties
  • Would having a Pure Class concept make sense or not?
  • Why catch invoked with success promise?
  • Match whole word if it meets a condition
  • Inserting items into array with bracket syntax doesnt affect length?
  • adding value inside an input - React
  • How does setInterval() run independently of sequential execution?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org