Problema ao listar itens do backend no meu frontend

import React, { Component, useEffect, useState} from 'react';

    import { View, Text, ScrollView, TextInput, TouchableOpacity, SvgUri } from 'react-native';

    import { useNavigation } from '@react-navigation/native';

    import api from '../../services/api';

    import styles from './styles';

    const Home = () => {

        const [quizzes, setQuizzes] = useState([]);

        const navigation = useNavigation();

        useEffect(() => {

            api.get('quizzes').then(response => {

                setQuizzes(response.data);

            });

        }, []);  

        function handleNavigationToQuiz() {

            navigation.navigate('Quiz', {

                user_id: 1,

                quiz_id: 2,

                jumps: 5

            });

        }  

        return (

            <>

                <ScrollView style={styles.container}>

                    <View style={styles.quizDownText}>

                        <Text style={styles.quizDownText}> QuizDown </Text>

                    </View>

                    <View style={styles.userInfo}>

                        <Text style={styles.userInfoText}> User </Text>

                        <Text style={styles.userInfoText}> Pontos: 100 </Text>

                    </View>

                    <View>

                        <TextInput style={styles.textInput}> <Text> Pesquisar </Text> </TextInput>

                    </View>

                    <Text>

                        {quizzes.map(quiz => (

                            <TouchableOpacity onPress={handleNavigationToQuiz}>

                                <Text> {quiz.name} </Text>`Texto pré-formatado`

                            </TouchableOpacity>

                        ))};

                    </Text>

                    

                </ScrollView>

            </>

        );

    }

    export default Home;

Nessa parte do meu código não estou conseguindo listar os nomes dos meus itens no frontend, se alguém puder ajudar, desde já agradeço.

Qual erro que está dando?

Tente passar a sua função com Async Await e depois passe para o useEffect, coloque um / na frente também:

async function LoadQuizzes() {
    await api.get('/quizzes')
      .then((response) => {
        setQuizzes(response.data);
      })
  }

useEffect(() => {
   LoadQuizzes();
}, [quizzes]);
1 curtida

[Unhandled promise rejection: Error: Request failed with status code 404]

  • node_modules\axios\lib\core\createError.js:15:17 in createError
  • node_modules\axios\lib\core\settle.js:16:9 in settle
  • node_modules\axios\lib\adapters\xhr.js:52:6 in handleLoad
  • node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
  • node_modules\react-native\Libraries\Network\XMLHttpRequest.js:567:4 in setReadyState
  • node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389:6 in __didCompleteResponse
  • node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 in emit
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425:19 in __callFunction
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:6 in __guard$argument_0
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373:10 in __guard
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
  • [native code]:null in callFunctionReturnFlushedQueue

Esse é o erro, continua dando errado, tudo que lista é um “;”.

Se a sua API estiver rodando em localhost dentro da sua services, mude o localhost pelo seu IP
import axios from ‘axios’;

const api = axios.create({
  baseURL: 'http://111.111.1.1:Porta'
})

export default api;

Eu já fiz isso, e realmente não estou entendendo o motivo de não funcionar.

Sou iniciante, então talvez esteja errando alguma bobagem.

Cara isso parece ser erro no seu Backend, faz o seguinte, verifique se a URL está correta, tenta dar um Get no Postman ou Insomnia ou no seu próprio Browser para ver se ele vai te retornar algo.

Caso ele te retornar 200, vai no seu browser do celular e jogue a sua url da API lá, verifique se ele vai te retornar o mesmo 200 success.