Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

309
Vistas
Warning: Can't call setState on a component that is not yet mounted. When calling an API

When I'm trying to run this code and the following error is shown to me.

Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the Api component.

what should i do to fix the issue?

class Api extends Component {     

    constructor(props){        

        super(props)
        this.state = {            
            data: [],            
        }

    }
    
    async componentDidMount(){

        this.apiCall()
        
    }
    
    async apiCall() {
        let resp = await fetch(URL)
        let respJson = await resp.json()
        this.setState({data:respJson.data.statistics})
        
    }

}


export default function App(){
    const api = new Api()
    api.componentDidMount()

    return (
        <View>
            <ScrollView style={styles.center}>
            
            <Text>{api.state.data.time}</Text>
            
            </ScrollView>
        </View>
    )
} 

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        padding: 20,
        alignItems: 'center',
        padding: 15,
    },
    title: {
        padding: 30,
    },
})

After uses Federkun solution i get this new error, im kind new with JS so I'm little lost.

i tryied to use a async function but keep showing the error.

Failed building JavaScript bundle. SyntaxError: 
C:\Users\yup\Documents\GitHub\LEARN_REACT\App.js: Unexpected reserved word 'await'. (54:19) 52 | 53 | React.useEffect(() => { > 54 | let resp = await fetch(URL) | ^ 55 | let respJson = await resp.json() 56 | setData({data:respJson.data.statistics}) 
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Api isn't really a react Component. No render function. And you would need to use it as part of your jsx, not like that.

But, there's a useful primitive that can hold state: hooks.

function useApi() {
  const [data, setData] = React.useState()

  React.useEffect(() => {
    async function load() {
      let resp = await fetch(URL)
      let respJson = await resp.json()
      setData({data:respJson.data.statistics})
    }

    load()
  }, [])

  return data
}

Which you can use like

export default function App(){
    const data = useApi()

    return (
        <View>
            <ScrollView style={styles.center}>
            <Text>{data.time}</Text>
            </ScrollView>
        </View>
    )
} 
about 4 years ago · Juan Pablo Isaza Denunciar

0

This is an extension to @Federkun answer, adding a few other useful props and fixing some issues,

You can rewrite your useApi hook to,

function useApi() {
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        let resp = await fetch('URL'); // your backend url goes here
        let respJson = await resp.json();
        setData(respJson);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  return { data, error, loading };
};

and to use,

export default function App() {
  const { data, loading, error } = useApi();

  if (loading)
    return (
      <View style={styles.container}>
        <Text>loading...</Text>
      </View>
    );
  return (
    <View style={styles.container}>
      {data && (
        <Text>{JSON.stringify(data)}</Text>
      )}
      {error && (
        <Text>{JSON.stringify(error)}</Text>
      )}
    </View>
  );
}

If you are still confused, you can see it in action at this live snack

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda