Z
Z
zlodiak2020-01-03 21:05:04
JavaScript
zlodiak, 2020-01-03 21:05:04

How to avoid looping when updating props?

I have a reducer that puts some array of values ​​in state. There is a component that receives these values ​​from the server and places them in state

function Victims(props) {
  useEffect(() => {
    apiRequest('/victims')
      .then(res => {
        store.dispatch(actionCreator(victims))
      })
  }, [props.victims]);

  return(
    <>
      Victims comp
    </>
  )
}

const mapStateToProps = state => {
  return {
    victims: state.victimsReducer.victims,
  }
}

export default connect(mapStateToProps, { })(Victims);


The problem is that I get an infinite process

получение данных -> помещение их в state

. This is because in the second argument of the useEffect hook I wrote:
[props.victims]

So this hook works, puts the result in state, but after that it works again because of [props.victims]. And so on ad infinitum

Please explain how to make the hook work once when the page is loaded for the first time, and then work only if the data came really new

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
brabrubra, 2021-01-08
@brabrubra

[JSON.stringify(props.victims)]have you tried?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question