Home > Software design >  How do I make two fetch calls in useEffect? ['Resolved']
How do I make two fetch calls in useEffect? ['Resolved']

Time:09-10

I am starting the development of the project and faced with the following problem "Error: Too many rerenders. React limits the number of renders to prevent an infinite loop." I'm trying to use several fetch requests in useEffect. i.e. I want these two requests to be executed only once when the component is launched. How can this be done? enter image description here

  const UserProfile = () => {

  const [newParams, setNewParams] = useState({
    surname: '',
    name: '',
    middlename: '',
    organization: '',
    email: '',
    phone: '',
    department: '',
    position: '',
    login: '',
    ScheduleId: ''
  })

  const [users, setUsers] = useState([])

  const [workSchedule, setWorkSchedule] = useState(
    []
  )

  const [workStatus, setWorkStatus] = useState(false)

  useEffect(() => {

    const fetch1 = fetch('/profile')
      .then(res => res.json())
      .then(users => {console.log(users); setUsers(users)});

    const fetch2 = fetch('/workSchedule'   '/'   '1')
      .then(res => res.json())
      .then(workSchedule => setWorkSchedule(workSchedule));
      
  }, [])

  function updateInput(event) {
    let temp = Object.assign({}, newParams);
    switch(event.target.className) {
      case 'CurrentDepartment':
        temp = Object.assign({}, newParams);
        temp = users[0]
        temp.department = event.target.value;
        setNewParams(temp)
      case 'CurrentPosition':
        temp = Object.assign({}, newParams);
        temp = this.state.users[0]
        temp.position = event.target.value;
        setNewParams(temp)
      default:
        console.log("Failed");
    }
  }

  function uploadNewDate() {

    let temp = users[0]

    fetch('/update-user', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': '<calculated when request is sent>'
      },
      body: JSON.stringify(temp)
    }).then(function(response) {
      console.log(response)
      return response.json()
    });
  }

  function updateUserStatus() {
    var date = new Date();
    let workStatus = date.getDay();
    if (workStatus > 5 && workStatus < 8) {
      workStatus = true
    } else {
      workStatus = false
    }
    
    setWorkStatus(workStatus)
  }
      
      return (
        <div className="Frame">
          {users.map((user, index) => {
            return (
              <div className="Profile" key={"profile"   index}>
                <div className="UserProfile">
                  <a className="ApproveButton" onClick={uploadNewDate}></a>
                  <div className="UserIcon">
                    <div className="Icon"></div>
                  </div>
                  <div className="UserInfo">
                    <div className="UserFIO">
                      <div id="Surname" className="Surname">{user.surname}</div>
                      <div className="Name">{user.name}</div>
                      <div className="MiddleName">{user.middlename}</div>
                    </div>
                    <p className="UserOrganization"></p>
                  </div>
                  <div className="UserStatus">
                    {workStatus?(
                      <>
                        <span className="OutputStatus"></span>
                        <h2 className="Status Status-output">Выходной</h2>
                      </> 
                    ):(
                      <>
                        <span className="WorkStatus"></span>
                        <h2 className="Status Status-working">Рабочий</h2>
                      </>
                    )}
                  </div>
                  <div className="UserContacts">
                    <div className="Contacts">
                      <a href="mailto:[email protected]">{user.email}</a>
                      <a href="tel:89124566734">{user.phone}</a>
                    </div>
                  </div>
                </div>
                <div className="OrganizationInfo">
                  <div className="UserDepartment">
                    <div className="Department">Отдел</div>
                    <input id="Department" className="CurrentDepartment" defaultValue={user.department} onChange={updateInput}></input>
                  </div>
                  <div className="UserPosition">
                    <div className="Position">Должность</div>
                    <input id="Position" className="CurrentPosition" defaultValue={user.position} onChange={updateInput}></input>
                  </div>
                </div>
                <div className="WorkSchedule">
                  <div className="Schedule">
                    <Link to="/work-schedule">График работы</Link>
                    <div className="WorkTime">
                      <div className="LeftColumn">
                        <div>Понедельник</div>
                        <div>Вторник</div>
                        <div>Среда</div>
                        <div>Четверг</div>
                        <div>Пятница</div>
                        <div className="output_day">Суббота</div>
                        <div className="output_day">Воскресенье</div>
                      </div>
                      {workSchedule.map(workSchedule => {
                        updateUserStatus()
                        return (
                          <div className="RightColumn">
                            <div>{workSchedule.monday}</div>
                            <div>{workSchedule.tuesday}</div>
                            <div>{workSchedule.wednesday}</div>
                            <div>{workSchedule.thursday}</div>
                            <div>{workSchedule.friday}</div>
                            <div className="output">{workSchedule.saturday}</div>
                            <div className="output">{workSchedule.sunday}</div>
                          </div>
                        )
                      })}
                    </div>
                  </div>
                </div>
                <div className="UserLogin">
                  <div className="Login">
                    <p>Логин</p>
                    <p>{user.login}</p>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      );
}

export default UserProfile;

CodePudding user response:

Your problem doesn't have anything to do with useEffect. You're calling updateUserStatus() on every render:

                      {workSchedule.map(workSchedule => {
                        updateUserStatus()
                        return (

This updates the state of the component by calling setWorkStatus, which will trigger a re-render and start the process all over again. Did you mean to use updateUserStatus as an event handler instead?

  • Related