1
votes

How do I get the newly updated data from react hooks or useEffect?

I loaded the parent components with the title: Shoes then change the input to "New Shoes" but the data inside my child components doesn't change, its still "Shoes". how do I get it updated?

in the parent components:

<UrlInput
   value={url}
   title={title}
   baseURL={baseURL}
   onChange={this.onURLChange}
/>

Child component

const UrlInput = ({title}) => {
    const [newTitle, setTitle] = useState(title);

     useEffect(() => {
         console.log(title)
         setTitle(newTitle)
     })

  return (

  );
};
3
Why Is the title variable with a capital T in your useState constructor?Towerss

3 Answers

3
votes

You should add title as a dependency to useEffect and update state with title and not newTitle. Also the original state needs to be set with title and not Title.

const UrlInput = ({title}) => {
    const [newTitle, setTitle] = useState(title);

     useEffect(() => {
         console.log(title)
         setTitle(title)
     }, [title]);

  return (

  );
};

P.S. Also its an antipattern to copy props into state when state is directly derivable from props unless you need to modify the state locally.

1
votes
const UrlInput = ({title, ...rest}) => {
    const [newTitle, setTitle] = useState(title);

     useEffect(() => {
         console.log(title)
         setTitle(title)
     },[title]) 

  return (

  );
};

try replacing the code with the above one .You should pass a new value into setTitle() you were passing the same variable that stored the previous value.

0
votes

For the get, any state-specific change in a component use the useEffect(() => {},[specific condition here]).

You can follow this code here.

in the parent components:

const [title, setTitle] = useState('');  // initial state parent 
const onURLChange = e => setTitle(e.target.value) ; set state parent from children triger 

<UrlInput
    value={url}
    title={title}
    baseURL={baseURL}
    onChange={this.onURLChange}
/>

Child component

const UrlInput =props => {
    const [newTitle, setTitle] = useState(props.Title);

     useEffect(() => {
         console.log(title)
         setTitle(newTitle)
     },[props.Title])

  return (

  );
};