Home > front end >  Updating state with axios response data in reactjs
Updating state with axios response data in reactjs

Time:08-02

I am building a website using nextjs and axios. Users can apply to become a member and then be approved by admins. In the admin dashboard I initially load the users and the unapproved users and display them in a list. When an admin clicks on a button the unapproved user should be approved. The functionality works. The only aspect I can't figure out is how to update the state.
Here is my code:

const AdminIndex = () => {
  const [users, setUsers] = useState([])
  const [unapprovedUsers, setUnapprovedUsers] = useState([])

  useEffect(() => {
    loadUnapprovedUsers()
    loadUsers()
  }, [])

  const loadUnapprovedUsers = async () => {
    const { data } = await axios.get('/api/admin/unapprovedUsers')
    setUnapprovedUsers(data)
  }

  const loadUsers = async () => {
    const { data } = await axios.get('/api/admin/users')
    setUsers(data)
  }

  const approveUnapprovedUser = async (email) => {
    try {
      const { data } = await axios.put(
        `/api/admin/approveUnapprovedUser/${email}`
      )
      setUnapprovedUsers([]) // only remove the approved user
      setUsers(...data) // include the approved user into the array
    } catch (err) {
      console.log(err)
    }
  }
}

I am trying to remove the approved user from the unapprovedUsers array and try to add the user to the users array, hence updating the UI. The response returned by axios is an object, which doesn't make things easier.

I would be very thankful for any kind of help!

CodePudding user response:

Just try to filter the unapprovedUsers with the users that don't have that email, also add the approved user to users state

const AdminIndex = () => {
  const [users, setUsers] = useState([])
  const [unapprovedUsers, setUnapprovedUsers] = useState([])

  useEffect(() => {
    loadUnapprovedUsers()
    loadUsers()
  }, [])

  const loadUnapprovedUsers = async () => {
    const { data } = await axios.get('/api/admin/unapprovedUsers')
    setUnapprovedUsers(data)
  }

  const loadUsers = async () => {
    const { data } = await axios.get('/api/admin/users')
    setUsers(data)
  }

  const approveUnapprovedUser = async (email) => {
    try {
      const { data } = await axios.put(
        `/api/admin/approveUnapprovedUser/${email}`
      )
      setUnapprovedUsers(prev => prev.filter(user => user.email !== email)) // only remove the approved user
      setUsers(prev => [...prev, data]) // include the approved user into the array
    } catch (err) {
      console.log(err)
    }
  }
}

  • Related