Search code examples
reactjsaxiosreact-hooksuse-effect

I want to be able to use useEffect always that I change the name of my group


useEffect(() => {
  Axios.get(`https://taskcontrolapp.herokuapp.com/taskcontrol/grupo/${props.id}`)
    .then(response => {
      setGrupo(response.data)
    }).catch(error => {
      console.log(error)
    })
}, [])

I have a object Grupo{ grupo_id and grupo_nome } and i want to change grupo_nome and make useEffect run again, already tried many variables as parameter and never works.


Solution

  • Per several articles and the react docs, putting this in useEffect like this is bad practice.

    It is recommended you either wrap it in a useCallback that is async, or wrap it in a function inside the useEffect, then call the function in useEffect.

    See these articles here:

    The Abramov guy

    Official docs on custom hooks

    useEffect(() => {
      async function someFunc () {
       await Axios.get(`https://taskcontrolapp.herokuapp.com/taskcontrol/grupo/${props.id}`)
        .then(response => {
          setGrupo(response.data)
        }).catch(error => {
          console.log(error)
        })
     }
    
    someFunc()
    
     return () => {
       // do some clean up here 
     }
    
    // Note the dependency array here...
    }, [props.id, grupo_nome])