React infinite loop returned by array even with dependency added

Viewed 231

I am trying to add the values of bookButton to the array, serviceList1 in the useEffect hook and this is what I came up with. The problem is, the array returned an infinite loop even when I have added the dependencies below. console.log(serviceList1) returns an infinite loop of false, followed by trues eventhough so far my serviceList1 array has only one value, false.

const [serviceList, setServiceList] = useState([]);
var [bookButton, setBookButton] = useState(false);
const [serviceList1, setServiceList1] = useState([]);

useEffect(()=>{
        Axios.get('http://localhost:8800/viewall')
        .then((response) => {
            setServiceList(response.data);
            serviceList.filter(function(serv){
                    if(serv.userId === userId){
                        setBookButton(false);
                        // setServiceList1([...serviceList1, bookButton]);
                        // setServiceList1(state => [...state, bookButton]);
                    }
                    else{
                        setBookButton(true);
                        // setServiceList1([...serviceList1, bookButton]);
                        // setServiceList1(state => [...state, bookButton]);
                    }
                setServiceList1([...serviceList1, bookButton]);
            }
            );

            console.log(serviceList1);
        })
    }, [serviceList1, serviceList, bookButton, userId]);

Anyone knows the problem with my code? Appreciate the help, thank you so much!

EDIT: I have tried removing the bookButton, serviceList1, serviceList dependencies, and now the array returns empty string.

2 Answers

Your effect updates serviceList, serviceList1, and bookButton when it runs, and because you've listed those as dependencies your effect runs whenever they change, hence the infinite loop.

Remove serviceList, serviceList1, and bookButton from the dependency list.

You are doing setState in each iteration of serviceList array by using filter method. That's leading to the infinite render loop.

useEffect(()=>{
  Axios.get('http://localhost:8800/viewall')
  .then((response) => {
      setServiceList(response.data);
      //if serv.userId === userId, Array.prototype.some will return true
      const hasBookButton = !response.data.some((serv) => serv.userId === userId)
      setBookButton(hasBookButton)
      setServiceList1(currentList => [...currentList, hasBookButton]);
  })
}, [userId]);
Related