Home > database >  How to render new data (or GET new) after making a POST request with axios?
How to render new data (or GET new) after making a POST request with axios?

Time:06-10

I'm using mockapi.io to practice with Axios API call

After I make a POST request, which create a new data, I want to render FlatList with the updated data. I'm thinking of making a new GET request to do that, but I'm not succeeded with it.

I need help

Here is where I call GET request, which already have mock data, and use FlatList to view it

ListScreen.js

class ListScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
        }
    }
    componentDidMount() {
        axios.get('insert url')
            .then(res => {
                this.setState({
                    data: res && res.data ? res.data : []
                })
            })
            .catch(err => {
                console.log('Run into problem')
            })
    }
    render() {
        const { data } = this.state;
        return (
            <View>
                <FlatList
                    data={data}
                    renderItem={({ item }) => {
                        return (
                            <Item
                                name={item.lastName}
                                phone={item.phoneNumber}
                            />
                        );
                    }}
                    keyExtractor={(item) => item.id}
                />
            </View>

And here is where I call POST request

class Create extends Component {

    handleSubmitData = (value) => {
        console.log('check value: ', value)
        axios.post('insert url', {
            lastName: `${value.Name}`,
            phoneNumber: `${value.Phone}`,
        })
            .then((response) => {
                console.log('here is what you upload: ', response.data)
            })
            .catch((err) => {
                console.log('Run into problem')
            })
    }
    render() {
        return (
            <CreateForm
                handleSubmitData={this.handleSubmitData}
            />
        )
    }
}

The CreateForm component looks something like this

class CreateForm extends Component {
    render() {
        const { handleSubmit } = this.props;
        return (
            <View>
                <View>
                    <Field
                        name="Name"
                        component={}
                    />
                    <Field
                        name="Phone"
                        component={}
                    />
                </View>
                <View>
                    <Button
                        title='Save'
                        onPress={handleSubmit(this.props.handleSubmitData)}
                    />
                </View>
            </View>
        )

CodePudding user response:

This can be done by lifting the state up, from ListScreen to ListScreen's parent.

In ListScreen, take out the state and move into its parent:

    this.state = {
        data: [],
    }

Pass the state down to ListScreen as a prop, also pass the fetch function (see below):

<ListScreen data={this.state.data} fetchListData={this.fetchListData} />

Change ListScreen's render function to access the data from props:

const { data } = this.props;

Move the axios.get() out of ListScreen and into a method on the parent component.

class App extends Component {
    fetchListData() {
        axios.get('insert url')
            .then(res => {
                this.setState({
                    data: res && res.data ? res.data : []
                })
            })
            .catch(err => {
                console.log('Run into problem')
            })
    }
}

In ListScreen, call the function in componentDidMount:

componentDidMount() {
    this.props.fetchListData();
}

Alternatively, you could call it in the parent component's componentDidMount(). This might be preferred if you render multiple ListScreen's for example.

Finally, in the Create component, pass the fetch function:

<Create fetchListData={this.fetchListData} />

Call it on successful creation:

        .then((response) => {
            this.props.fetchListData();
            console.log('here is what you upload: ', response.data)
        })

CodePudding user response:

As I see in your code, when you are making a POST request it wont display an updated data to your screen because there is no GET request callback upon the success result.

Suggesting you are not using redux , in ListScreen.js you could wrap the GET request into a function and call it in componentDidMount(). It should be look like:

const getData () => {
    axios.get('insert url')
            .then(res => {
                this.setState({
                    data: res && res.data ? res.data : []
                })
            })
            .catch(err => {
                console.log('Run into problem')
            })
}


componentDidMount() {
    this.getData()
}

Therefore, you need to pass or drill the GET request function into your child component as a props and use it in a POST request callback. The final POST request method should be look like:

handleSubmitData = (value) => {
        console.log('check value: ', value)
        axios.post('insert url', {
            lastName: `${value.Name}`,
            phoneNumber: `${value.Phone}`,
        })
            .then((response) => {
                console.log('here is what you upload: ', response.data)
                getData()
            })
            .catch((err) => {
                console.log('Run into problem')
            })
    }

As you can see, after your POST request is finished, it will trigger a GET request to update your parent state, resulting a screen with an updated data. However, you have to make sure to pass your parameters correctly based on how your component structure is.

  • Related