Using useEffect with class Components

Viewed 4597

I have a class used to render a list of users from a database

    export default class Users extends React.Component {
    
      constructor() {
        super()
      this.state = {
          data : [] //define a state  

        }
      }
    
    renderUsers = () => {
        useEffect(() => {
          fetch('exemple.com')
            .then((response) => response.json())
            .then((json) => this.setState({data: json.result})) // set returned values into the data state
            .catch((error) => console.error(error))
        }, []);
    
       return  this.state.data.map((value,key)=>{ // map state and return some views 
            ......
          })
     }
    
     render() {
        return (
                 <View style={{ flex: 1 }}>
              {this.renderUsers()} //render results
            </View>
    
        );
      }
    }

The problem is this code will throw the following error :

Invalid Hook call, Hooks can be called only inside of the body component

I think is not possible to use hooks inside class component.. If it's not possible what is the best approach to fetch data from server inside this class ?

2 Answers

You cannot use hooks in a class component. Use componentDidMount instead.

Hooks can be used only in functional components.

You could rewrite your component to be a functional one like so:

export default Users = () => {
    const [data, setData] = useState([]);

    useEffect(() => {
        fetch('exemple.com')
            .then((response) => response.json())
            .then((json) => setData(json.result)) // set returned values into the data state
            .catch((error) => console.error(error))
    }, []);

    const renderUsers = () => {
        return data.map((value, key) => {
            // DO STUFF HERE
        })
    }

    return (
        <View style={{ flex: 1 }}>
            {renderUsers()} //render results
        </View>
    )

}
Related