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 :
  • How to decrypt the encrypted UID using firestore security rules?
  • javascript - if and or (||) statement
  • How to get overlay to position on an image?
  • cannot set checked of undefined (saving checkboxs w/ localStorage)
  • how can I send a data by ajax and the url has a variable value in the middle of the link
  • React Click Counter: Updating State of just one element
  • Having trouble with undefined output from this code below
  • Showing an image based on a number range in Javascript
  • Check which condition in IF statement is true
  • How do I reset the numbers after calculating the Total
  • Site loads slowly
  • How to insert href URL to Javascript var?
  • How can I use an array across multiple files?
  • Difference between $('.huyen') and $('.huyen')[0]
  • Using two array values in foreach loop
  • navigator.mediaDevices.enumerateDevices() returns empty labels
  • JavaScript positional property access in Objects
  • Is this possible to setInterval with custom ID so I can clear it later on from another services?
  • How to focus bootstrap select picker
  • Calling firebase functions returns null
  • Set a variable equal to null if it is not included in an array?
  • Remove Duplicate object from Array Deep Check
  • Check if array of objects key is empty and splice it
  • How to find next birthday date from list of date from date now?
  • Reorder array of objects based on array of strings?
  • Replace ISO-Date with normal Date in HTML Document via Widget
  • React setState not changing the state
  • Bitwise operations in JavaScript
  • react slide out menu state = not setting state?
  • .map() function and deleting a row from a table with ReactJS
  • Vanilla JavaScript in Svelte
  • Filter My Array / JSON Data (including multi values) Based on Multiple Criteria in JavaScript?
  • Unnecessary rerenders with useContext
  • Implement HTML input phone mask XXX-XXX-XXXX
  • create variable by matching variable value to object value?
  • Parsing Data in Google Sheets From an Object
  • How to obtain a user input value from an image input in Javascript?
  • Is it posible to implement functions that use non blocking setTimeout synchronically?
  • What would be consider as my local scope in this function?
  • regex expression for string.split() that splits a string on urls
  • Vue props become null on $router.go(-1)
  • How can I set my local date in javaScript
  • Why my state does not change on click event with setState
  • How to fetch data from API using id in reactJS?
  • What is the problem in this recursive javascript function? [JS]
  • How to store & retrieve an object as a value in option of select element?
  • Select Text in DIV with specific range using JavaScript
  • JavaScript error executing a function: 2 arguments required but only 1 present
  • How to remove a specific character from array in JS?
  • Get Text content of 3rd <p> element inside <div> element
  • HTML li element will not except
  • How can I render nested objects and arrays in JSX?
  • using .find or .index of inside .find
  • Unable to add to an array of objects copied from state
  • Find an object properties by searching for keys by a string, and if one is true, return as true
  • Why does awaiting a setInterval promise inside of a while loop cause the amount of calls to stack up?
  • How to send data attribute to php variable using jquery?
  • In Javascript or jQuery how to scroll so that an element inside another div is centered vertically and horizontally
  • How to create an animated stackoverflow icon
  • Why is my javascript function being printed as undefined?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org