Search code examples
reactjsamazon-web-servicesreact-hooksuse-effectamazon-ivs

ReactJS: useEffect update metadata on every request of aws IVS chaannel


I would like to perform the continuous process as this below link to update the metadata of the aws IVS stream.

I have managed with the useEffect hook but it is not updating the value and throws the undefined error.

https://codepen.io/amazon-ivs/pen/XWmjEKN?editors=0011

function AppComponent(props) {

  const [metaData, setMetaData] = useState(null)

  useEffect(() => {
    const data = props.metadata
    const initData = async () => {
      setMetaData(data)
    }
    initData()
  }, [metaData])

  return (
    <div>
      <h2>{metaData.question}</h2>
    </div>
  )
}

Solution

  • Ok, I am a bit confused about this code snippet. if you assume that you receive in your props metadata then probably you don't need state at all, and your code should look like below

    function AppComponent(props) {
    
      return (
        <div>
          <h2>{props.metadata.question}</h2>
        </div>
      )
    }
    

    Regarding your code overall, you have created metaData with initial value null, so metaData.question will throw error on the initial run. It doesn't make no sense to run setMetaData asynchronously. Also you have subscribed to metaData change in your hook, but only place where you update it is your hook, it will cause also infinite loop. It would be better if you will provide more information about your issue and make this question not so wide

    If you use only some properties from the object you are passing then you probably don't need to pass whole object as a prop, but it would be better to pass props that you use, as any change on the object, you are passing will cause rerendering of the component. Also you can try to use React.memo to avoid unnecessary rerendering cycles.