Milos
Milos

Reputation: 619

Update components based on props

I have one reusable component which receives prop series. That prop contains the data object. Depends on data.length I need to update the component. In case one, data.lenght is 20, and in case two data.length is 6. But when I try to achieve this, component renders only the case where data.length is 20, and when I hit refresh it takes the second case where data.length is 6. I have tried using useEffect() hook but it doesn't work. Apparently I'm missing something. Here is what I've tried so far

const ReusableComponent = ({series}) => {
     const [propSeries, setSeries] = useState(series.data.length);
     useEffect(() => {
        if(propSeries > 6) {
          // do something
        }
     }, [propSeries])
}

Here is the example of my problem: example. What am I doing wrong?

Upvotes: 0

Views: 57

Answers (2)

Abdullah Abid
Abdullah Abid

Reputation: 1661

The useEffect hook will execute when the component loads set the Series inside the useEffect hook before checking for the length.this way you could implement componentWillReceiveProps functionality using hooks

 const [propSeries, setSeries] = useState(0);
  useEffect(() => {
    setSeries(series.data.length);
    if (propSeries > 6) {
      alert("Prop Series is Greatar than 6");
    }
  }, [series, propSeries]);

i created a working example, CodeSadbox here

Hope this helps

Upvotes: 0

maten
maten

Reputation: 586

Why do you set your props into your state? You could just something like this:

const ReusableComponent = ({series}) => {
     useEffect(() => {
        if(series.data.length > 6) {
          // do something
        }
     }, [series])
}

Upvotes: 1

Related Questions