Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

308
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda