Updating state with new data in React: A step-by-step guide

Recently, I delved into the world of reactjs and embarked on a journey to fetch data from an API:

constructor(){
    super();
    this.state = {data: false}
    this.nextProps ={};

    axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(response => {
            nextProps= response;
        });
  }

Once the promise fulfills with the desired data, my goal is to update the state accordingly:

componentWillReceiveProps(nextProps){
    this.setState({data: nextProps})
  }

I am currently facing issues setting the state with the data received from the API. Any insights on how to achieve this effectively? As of now, the state remains unset.

For reference, here's a link to the jsbin: https://jsbin.com/tizalu/edit?js,console,output

Answer №1

It is common practice to perform an AJAX request in the componentDidMount lifecycle method. For more details, refer to the React documentation: https://facebook.github.io/react/tips/initial-ajax.html

Retrieve Initial Data with AJAX
Retrieve data in componentDidMount. Once the response is received, save the data in state to trigger a UI update.

To implement this convention, you can use this code snippet: https://jsbin.com/cijafi/edit?html,js,output

class App extends React.Component {
  constructor() {
    super();
    this.state = {data: false}
  }

  componentDidMount() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(response => {
            this.setState({data: response.data[0].title})
        });
  }

  render() {
    return (
     <div> 
      {this.state.data}
     </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

For another demonstration, check out this example (http://codepen.io/PiotrBerebecki/pen/dpVXyb) showcasing two approaches using either jQuery or Axios libraries.

Complete code below:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      time1: '',
      time2: ''
    };
  }

  componentDidMount() {
    axios.get(this.props.url)
      .then(response => {
        this.setState({time1: response.data.time});
      })
      .catch(function (error) {
        console.log(error);
      });

    $.get(this.props.url)
      .then(result => {
        this.setState({time2: result.time});
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <div>
        <p>Time via axios: {this.state.time1}</p>
        <p>Time via jquery: {this.state.time2}</p>
      </div>
    );
  }
};


ReactDOM.render(
  <App url={"http://date.jsontest.com/"} />,  document.getElementById('content')
);

Answer №2

Feel free to test out the code snippet below and reach out if you require any additional assistance.

var YourCustomComponent = React.createClass({
  componentDidMount: function() {
    var that = this;
    // Your API call will be made here, and once the response is received, set the state as shown below
    // This is just a sample using AJAX for demonstration purposes
    $.ajax({
      url: 'YOURURL',
      dataType: 'json',
      type: 'POST',
      data: data,
      success: function(response) {
        that.setState({data: response})
      }
    });
  },
  render: function() {
    return ();
  }
});

Appreciate your time!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What kind of Antd type should be used for the form's onFinish event?

Currently, I find myself including the following code snippet repeatedly throughout my project: // eslint-disable-next-line @typescript-eslint/no-explicit-any const handleCreate = (input: any): void => { saveToBackend({ title: input.title, oth ...

React/Javascript - Executing Function returns prematurely

I have been working on a function that takes an object and iterates through it to create a search query. However, the issue I'm facing is that the function returns before I finish looping through the object: export default function buildQuery(query) ...

Managing JSON data retrieval and manipulation with REST API in Node.js and MongoDB

My technology stack includes Node.js and MongoDB with a rest api. The input data I'm dealing with looks like this: var doc={"name":"ABX", duedate : new Date() } Before sending it to the server, I stringify the data: /rest/update?doc=JSON.s ...

Tips on utilizing setInterval in a Vue component

When defining the timer in each individual my-progress, I use it to update the value of view. However, the console shows that the value of the constant changes while the value of the view remains unchanged. How can I modify the timer to successfully change ...

The persistent animation of the Drawer MUI component in React with MUI can be frustratingly slow at times

I am currently developing an application where we have a left drawer and a main component aligned in the right direction. https://i.stack.imgur.com/1VOHm.png When I close the drawer, the main component adjusts to occupy the remaining space by moving slig ...

The 'toBeInTheDocument' property is not found on the 'Matchers<HTMLElement>' type

Having trouble setting up testing for a components library. Despite trying various examples and similar threads, I have not been successful. I can confirm that my setupTests.ts file is being loaded correctly (verified through a console.log). Additionally, ...

updating the HTML DOM elements using JavaScript is not yielding any response

One way that I am trying to change the background of a div is by using a function. Below is an example of the html code I am working with: $scope.Background = 'img/seg5en.png'; document.getElementById("Bstyle").style.background = "url("+$scope.B ...

Is there a way to establish a connection with a secondary Firestore database in Node.js, allowing for the use of multiple Firestore databases

I have set up multiple firestore databases within my project. Using the command line, I created these databases and can view them in the Firestore Databases preview by following the instructions outlined here: https://cloud.google.com/blog/products/databas ...

What are the advantages of incorporating Express with ReactJS?

Recently, I started working on a fresh ReactJS application and in the past, I relied on Express for server-side rendering in my projects. This was mainly because routing in production mode would not function properly without it. However, I've now com ...

What is the best way to modify the font color of DialogTitle and DialogContent in Material UI within a react.js environment?

Is there a way to customize the font/text color in DialogTitle and DialogContent components using Material UI in react.js? I have successfully changed the background color for the Dialog, but it seems changing the font color for Dialog and DialogContent i ...

What is the process for recording information using a static method in TypeScript within a class?

For my school project, I'm struggling to retrieve the names from a class using a method. One class creates monsters and another extends it. abstract class genMonster { constructor( public id: string, public name: string, public weaknesse ...

Sending form information through AjaxPassing information from a form using

Currently, I am working on a project where one page opens a thickbox of another page that contains a form. Once the form is submitted and data is written to the database, I need the parent page of the thickbox to update specific rows of the form that have ...

Get geographical coordinates (latitude and longitude) from a database and pass them to a PHP

I have been working on plotting latitude and longitude data from a MySQL database onto a PHP page. Initially, I was able to display the marker without using JSON with the following code: <? $dbname ='insert mysql database name'; ...

Detecting click events in D3 for multiple SVG elements within a single webpage

My webpage includes two SVG images inserted using D3.js. I am able to add click events to the SVGs that are directly appended to the body. However, I have encountered an issue with another "floating" div positioned above the first SVG, where I append a dif ...

How can I troubleshoot the unresponsive remove div function on my website?

My code is running fine on CodePen (link provided below), but for some reason, it's not working properly in the web browser. I am executing the code from localhost and the button isn't responding as expected. CODE Here is my Visual Studio code ...

Error: Unable to access the 'address' property of a null object

I am a beginner in the realm of react and have encountered an issue with my app, which is a simple e-commerce platform. The problem arises when I try to enter the shipping address during the checkout process, as it throws an error. TypeError: Cannot read ...

Implement an event listener on the reference obtained from the React context

Within the React context provider, a ref is established to be utilized by another component for setting a blur event listener. The issue arises when the blur event fails to trigger the listener. The following is a snippet of code from the context provider ...

Include a <div> element to display the date in an HTML format, ensuring that the days and months

I am working on a project where I have a list of dates and I need to format them by adding div tags to separate the days, months, and years into different divisions. <div class="campaign">30/11/2016 - <a href="#" target="_blank">Dummy Text& ...

What is the method for retrieving the IDs of checkboxes that have been selected?

I attempted running the following code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://static.jstree.com/v.1. ...

Even when it appears to be chaotic, the TypeScript array of numbers always manages to find its way back to being sorted

I recently developed a function that aims to verify if an array of numbers is sorted: const checkIfSorted = (numbers: number[]) => { return numbers === numbers.sort((a, b) => a - b); }; checkIfSorted([4, 2, 8, 7, 3, 10, 1, 5, 9, 6]); // This cur ...