How to use useState hook to set value within FormDataConsumer

367 views Asked by At

I am having to set a const value using useState hook in FormDataConsumer. This is necessary because the value of the const can only be gotten within FormDataConsumer. This const value will be used as a prop to another component. The problem I am having is the error message below. What is the best way to do this? Thanks in advance

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

//const initialized here
    const [outletsList, setOutletsList] = useState([]);

 
//the place where the const must be set
   

                     <FormDataConsumer>
                      {({ formData, ...rest }) => {
                        //console.log(`formData: ${JSON.stringify(formData)}`)
                        //console.log(`rest: ${JSON.stringify(rest)}`)
        
                        let s = GetOutletsBySalesRep({
                          distributorkey: formData.distributorid,
                          salesrep: formData.salesrep,
                        });
        
                        **setOutletsList(s);**
                      }}
                    </FormDataConsumer>
1

There are 1 answers

0
Kia Kaha On BEST ANSWER

The error you get is because of the way React itself works - you update a state variable which makes the component to rerender and on each render you set the state again ... so you end up in an endless loop.

To escape it you should either set a condition upon which the state will be updated e.g.

if(outletsList.length === 0) setOutletsList(s);

Or use a reference to save the result through the useRef hook updating it's current property because this operation doesn't trigger a rerender.

const outletsListRef = useRef();

... 

outletsListRef.current = s;

Although not sure why you would need to save it and not rerender the component.