Reactjs updating data

I javascript i am used to you just calling a function after i want to update
But here in reactjs it seems to be different.

  componentDidMount() {
        this.getData();
    }
    async getData() {
        const url = this.state.url;
        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
        this.setState({ loading: false });

    }
    uploading() {

        const item =
        {   title: 'new',
            price: 3,
            description: 'test',
            quantity: 5
        };

        fetch('api/Upload', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(item)
        }).then(response => response.json())
          .catch(error => console.error("unable to achive this", error))
            .then(data => {
                console.log('succes', data);
                this.getData(); // <-- the function i want to update
            });

when i try to call the “getData()” i get a error and it does not update it
How do i achive this?

I have heard of componentDidUpdate()
so i tried to call it after all the other functions and pass that function in there but
it is not working either.

When updating the state depends on the previous state, you should be using the previous state from a callback.

this.setState((previousState) => {
  const { url } = previousState;
  const response = await fetch(url);
  const data = await response.json();

  return { loading: false });
});

More information:

However, getting a URL seems like a strange thing to do in the state, unless it’s a user provided URL.

Are you sure you shouldn’t be using props for that?

  • Props should only be handled by the parent of a component, and is used to supply data to a component.
  • State should only be handled by a component itself, and is used to manage the variables of a component.

Due to the lack of information, it’s difficult to give further comment. Could you edit your post to share the full component?

1 Like

of course here is the full code:

import React, { Component } from 'react';

export class Upload extends Component {
    static displayName = Upload.name;

    constructor(props) {
        super(props);
        this.state = {
            Title: "empty",
            Price: 1,
            Description: "empty description",
            quantity: 2,
            loading: true,
            url: 'api/Upload',
            person: null
        };
       
    }

    componentDidMount() {
        this.getData();
    }



    async getData() {
        const url = this.state.url;
        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
        this.setState({ loading: false });


    }
    uploading() {

        const item =
        {   title: 'new',
            price: 3,
            description: 'test',
            quantity: 5
        };

        fetch('api/Upload', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(item)
        }).then(response => response.json())
          .catch(error => console.error("unable to achive this", error))
            .then(data => {
                console.log('succes', data);
                this.getData();
            });
           
    }

    componentDidUpdate() {
       
    }


    render() {
       
    return (
            <div>
            <h1>Upload here</h1>
            { this.state.loading ? <div>Loading...</div> : <div>...person</div>}
            <button id="uploadbutton" onClick={this.uploading}>Upload the product</button>
            </div>
        );
    }

       
}

I simply want to update the console.log ( or list ) everytime i have used the getData() function so it shows the new data

You aren’t binding your methods. Either bind them in the constructor or use the arrow syntax (e.g. uploading = () => {} and getData = async () => {}).

I’m also not sure I understand the two separate fetch calls and for the one in uploading you want catch to come last in the chain.


Edit: Or if you want to use functional components How to fetch data with React Hooks?. Which I would suggest learning anyway. Using functional components and hooks is much cleaner and how most modern React code is written.

Yeah i will definitely do i saw some interesting articles about React Query
I am going to spend some time learning that allong with react hooks

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.