Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Save value from custom hook to state

$
0
0

I am trying to save a value from a custom hook, which is fetching data for the server, to functional component state with useState, because I later need to change this value and after the change it needs to rerender. So desired behaviour is:

  1. Set State variable to value from custom hook
  2. Render stuff with this state variable
  3. Modify state on button click
  4. Rerender with new state

What I tried is:

  • Set the inital value of useState to my hook:const [data, setData] = useState<DataType[] | null>(useLoadData(id).data)but then data is always empty.

  • Set the state in a useEffect() hook:

    useEffect(()=>{    const d = useLoadData(id).data    setData(d)}, [id])

    But this is showing me the Error warning: Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

  • Doing this:

    const [data, setData] = useState<DocumentType[]>([])const dataFromServer = useLoadData(id).datauseEffect(()=>{  if (dataFromServer){    setData(dataFromServer)  }}, [dataFromServer])

    Leading to: ERROR: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

What would be a proper solution for my use case?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>