React Native request the api via navigation response

Asked

Viewed 331 times

1

Main.js

import React, { Component } from 'react';
import api from '../service/api';
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';

export default class Main extends Component {
    static navigationOptions = {
        title: 'JSHunt',
    };

    state = {
        lista: [],
    };

    componentDidMount() {
        this.loadProducts();
    }

    loadProducts = async () => {
        const response = await api.get("/tarefa/");
        const { lista } = response.data;
        this.setState({ lista });
    };

    renderItem = ({ item }) => (
        <View style={styles.listaContainer}>     
            <Text style={styles.listaDescription}>{item}</Text>
            <TouchableOpacity style={styles.listaButton} onPress={() => {
                this.props.navigation.navigate("Tarefa", { tarefa: item});
            }}>
                <Text style={styles.textButton}>Acessar</Text>
            </TouchableOpacity>
        </View>
    );

    render() {
        return (
            <View style={styles.listaContainer}>     
                <FlatList
                    contentContainerStyle={styles.list}   
                    data={this.state.lista}
                    keyExtractor={item =>item}
                    renderItem = {this.renderItem}
                />
            </View>
        );
    }
}

Task.js

import React from 'react';

import { Text} from 'react-native';

const Tarefa = ({navigation }) => {    
    console.log(navigation.state.params.tarefa);
    return (
        <Text>{navigation.state.params.tarefa}</Text>
    );   
};


export default Tarefa;

In the main I make a request for the API which returns me a list, when I click on one of the values of the list it goes to a new screen that is the task, and with this value I need to make a new request, it would be kind of detail.

Only that I am not able to make a new request only I can show the value that should be called for new request in "navigation.state.params.task"

would stay for example

http://localhost:8080/tarefa/navigation.state.params.tarefa

or as it appears on the screen

http://localhost:8080/tarefa/1

1 answer

0

Transform the task component into a class, and use the WillMount component to call the API:

 export default class Tarefa extends Component {

    componentWillMount() {
        " 1 - ---->Chamada API AQUI"
        " 2 - Guardar resposta com os detalhes no state"  
    }

    render() {
        return (
           <Text>"3 -> O que você quer renderizar com base dos detalhes do state"</Text>
        );
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.